Example usage for javax.imageio ImageIO read

List of usage examples for javax.imageio ImageIO read

Introduction

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

Prototype

public static BufferedImage read(ImageInputStream stream) throws IOException 

Source Link

Document

Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered.

Usage

From source file:ddf.catalog.transformer.OverlayMetacardTransformerTest.java

@Before
public void setUp() {
    final BiFunction<Metacard, Map<String, Serializable>, Optional<BufferedImage>> supplier = (metacard,
            arguments) -> {//from  ww w .  ja va2s. c o m
        try (final InputStream inputStream = getClass().getClassLoader().getResourceAsStream("flower.jpg")) {
            return Optional.ofNullable(ImageIO.read(inputStream));
        } catch (IOException e) {
            return Optional.empty();
        }
    };

    transformer = new OverlayMetacardTransformer(supplier);
}

From source file:de.awtools.basic.io.AWToolsIOUtils.java

/**
 * Konvertiert eine Klassenpfad-Resource in ein <code>Image</code>.
 *
 * @param resource Eine Resource die im Klassenpfad liegt.
 * @param classLoader Der zu verwendende Klassenlader.
 * @return Das geladene Image./*from   w ww.  j a  v a 2s .  co m*/
 */
public static Image loadImage(final String resource, final Class<?> classLoader) {

    try {
        URL imageURL = classLoader.getResource(resource);
        // An alternative loading function:
        // return Toolkit.getDefaultToolkit().createImage(imageURL);
        return ImageIO.read(imageURL);
    } catch (IOException ex) {
        log.error("Fehler: ", ex);
        throw new UnhandledException(ex);
    }
}

From source file:ImageUtils.java

/**
 * Resizes an image//from w  w w  . ja  v  a  2s .  c  o m
 * 
 * @param imgName The image name to resize. Must be the complet path to the file
 * @param type int
 * @param maxWidth The image's max width
 * @param maxHeight The image's max height
 * @return A resized <code>BufferedImage</code>
 */
public static BufferedImage resizeImage(String imgName, int type, int maxWidth, int maxHeight) {
    try {
        return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.ku.brc.util.thumbnails.ImageThumbnailGenerator.java

/**
 * Creates a thumbnail of the given image bytes.
 * /*from   www  .jav a2  s  .  c om*/
 * @param originalImageData the bytes of the input file
 * @param doHighQuality higher quality thumbnail (slower)
 * @return the bytes of the output file
 * @throws IOException if any IO errors occur during generation or storing the output
 */
public byte[] generateThumbnail(final byte[] originalImageData, final boolean doHighQuality)
        throws IOException {
    ByteArrayInputStream inputStr = new ByteArrayInputStream(originalImageData);
    if (inputStr != null) {
        BufferedImage orig = ImageIO.read(inputStr);
        if (orig != null) {
            if (orig.getHeight() < maxSize.getHeight() && orig.getWidth() < maxSize.getWidth()) {
                // there's no need to do anything since the original is already under the max size
                return originalImageData;
            }

            byte[] scaledImgData = GraphicsUtils.scaleImage(orig, maxSize.height, maxSize.width, true,
                    doHighQuality);
            return scaledImgData;
        }
    }
    return null;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String//w  ww  .  ja v a2 s .  co m
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImage(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    if (imageFile != null) {
        imageFile.delete();
    }
    return pdfFile;
}

From source file:org.jtalks.common.web.validation.ImageDimensionValidator.java

/**
 * Validate object with {@link ImageDimension} annotation.
 *
 * @param multipartFile image that user want upload as avatar
 * @param context       validation context
 * @return {@code true} if validation successfull or false if fails
 *///www  .j a v a  2  s .  c  o  m
@Override
public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext context) {
    if (multipartFile.isEmpty()) {
        //assume that empty multipart file is valid to avoid validation message when user doesn't load nothing
        return true;
    }
    Image image;
    try {
        image = ImageIO.read(multipartFile.getInputStream());
    } catch (Exception e) {
        return false;
    }
    return (image == null) ? false : image.getWidth(null) == imageWidth && image.getHeight(null) == imageHeight;
}

From source file:examples.gp.monalisa.gui.GeneticDrawingView.java

@Action
public void chooseImage() throws IOException {
    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File("."));
    fc.showOpenDialog(mainPanel);//from w  w w . j  a v a2s  .c o m
    File file = fc.getSelectedFile();
    targetImage = ImageIO.read(file);
    targetImageLabel.setIcon(scaleToImageLabel(targetImage));
    fittestDrawingView.setSize(targetImage.getWidth(), targetImage.getHeight());
}

From source file:com.o2d.pkayjava.editor.proxy.ResolutionManager.java

public static BufferedImage imageResize(File file, float ratio) {
    BufferedImage destinationBufferedImage = null;
    try {/*from w ww  .j  a va 2 s  .c  o m*/
        BufferedImage sourceBufferedImage = ImageIO.read(file);
        if (ratio == 1.0) {
            return null;
        }
        // When image has to be resized smaller then 3 pixels we should leave it as is, as to ResampleOP limitations
        // But it should also trigger a warning dialog at the and of the import, to notify the user of non resized images.
        if (sourceBufferedImage.getWidth() * ratio < 3 || sourceBufferedImage.getHeight() * ratio < 3) {
            return null;
        }
        int newWidth = Math.max(3, Math.round(sourceBufferedImage.getWidth() * ratio));
        int newHeight = Math.max(3, Math.round(sourceBufferedImage.getHeight() * ratio));
        String name = file.getName();
        Integer[] patches = null;
        if (name.endsWith(EXTENSION_9PATCH)) {
            patches = NinePatchUtils.findPatches(sourceBufferedImage);
            sourceBufferedImage = NinePatchUtils.removePatches(sourceBufferedImage);

            newWidth = Math.round(sourceBufferedImage.getWidth() * ratio);
            newHeight = Math.round(sourceBufferedImage.getHeight() * ratio);
            System.out.println(sourceBufferedImage.getWidth());

            destinationBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = destinationBufferedImage.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
            g2.drawImage(sourceBufferedImage, 0, 0, newWidth, newHeight, null);
            g2.dispose();

        } else {
            // resize with bilinear filter
            ResampleOp resampleOp = new ResampleOp(newWidth, newHeight);
            destinationBufferedImage = resampleOp.filter(sourceBufferedImage, null);
        }

        if (patches != null) {
            destinationBufferedImage = NinePatchUtils.convertTo9Patch(destinationBufferedImage, patches, ratio);
        }

    } catch (IOException ignored) {

    }

    return destinationBufferedImage;
}

From source file:ar.com.zauber.common.image.impl.AbstractImage.java

/**
 * Creates a thumbnail//from  w  w  w . j ava  2 s . c  om
 * 
 * @param is data source
 * @param os data source
 * @throws IOException if there is a problem reading is
 */
public static void createThumbnail(final InputStream is, final OutputStream os, final int target)
        throws IOException {
    final float compression = 0.85F;
    ImageWriter writer = null;
    MemoryCacheImageOutputStream mos = null;
    Graphics2D graphics2D = null;
    try {
        final BufferedImage bi = ImageIO.read(is);
        final Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("JPG");
        if (!iter.hasNext()) {
            throw new IllegalStateException("can't find JPG subsystem");
        }

        int w = bi.getWidth(), h = bi.getHeight();
        if (w < target && h < target) {
            // nothing to recalculate, ya es chiquita.
        } else {
            if (w > h) {
                h = target * bi.getHeight() / bi.getWidth();
                w = target;
            } else {
                w = target * bi.getWidth() / bi.getHeight();
                h = target;
            }
        }
        // draw original image to thumbnail image object and
        // scale it to the new size on-the-fly
        final BufferedImage thumbImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(bi, 0, 0, w, h, null);

        writer = (ImageWriter) iter.next();
        final ImageWriteParam iwp = writer.getDefaultWriteParam();
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(compression);
        mos = new MemoryCacheImageOutputStream(os);
        writer.setOutput(mos);
        writer.write(null, new IIOImage(thumbImage, null, null), iwp);
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (mos != null) {
            mos.close();
        }
        if (graphics2D != null) {
            graphics2D.dispose();
        }
        is.close();
        os.close();
    }
}

From source file:com.joliciel.jochre.graphics.ShapeFillerImplTest.java

@Test
public void testGetFillFactor(@NonStrict final JochreImage jochreImage) throws Exception {

    new NonStrictExpectations() {
        {//from ww  w . j av a 2  s.c  o  m
            jochreImage.normalize(255);
            returns(255);
            jochreImage.normalize(0);
            returns(0);
        }
    };

    for (int i = 0; i <= 2; i++) {
        String imageName = "";
        if (i == 0) {
            imageName = "AlephWithHoles.png";
        } else if (i == 1) {
            imageName = "TesWithHoles.png";
        } else {
            imageName = "AlephNoHoles.png";
        }
        LOG.debug(imageName);
        InputStream imageFileStream = getClass()
                .getResourceAsStream("/com/joliciel/jochre/test/resources/" + imageName);
        assertNotNull(imageFileStream);
        BufferedImage image = ImageIO.read(imageFileStream);

        ShapeInternal shape = new ShapeImpl();
        shape.setImage(image);
        shape.setJochreImage(jochreImage);
        shape.setTop(0);
        shape.setLeft(0);
        shape.setRight(image.getWidth() - 1);
        shape.setBottom(image.getHeight() - 1);

        ShapeFillerImpl shapeFiller = new ShapeFillerImpl();
        shapeFiller.getFillFactor(shape, 100);
    }
}