Example usage for javax.imageio ImageReader setInput

List of usage examples for javax.imageio ImageReader setInput

Introduction

In this page you can find the example usage for javax.imageio ImageReader setInput.

Prototype

public void setInput(Object input, boolean seekForwardOnly) 

Source Link

Document

Sets the input source to use to the given ImageInputStream or other Object .

Usage

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

private void convertByteImageToFile(byte[] imageByte, String path) throws Exception {
    System.out.println("path ...... convertByteImageToFile ......... " + path);

    ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
    Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");

    ImageReader reader = (ImageReader) readers.next();
    Object source = bis;//from w  ww .j  a  va 2 s  . c  o m
    ImageInputStream iis = ImageIO.createImageInputStream(source);
    reader.setInput(iis, true);
    ImageReadParam param = reader.getDefaultReadParam();

    Image image = reader.read(0, param);
    //got an image file

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
            BufferedImage.TYPE_INT_RGB);
    //bufferedImage is the RenderedImage to be written

    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, null, null);

    File imageFile = new File(path);
    ImageIO.write(bufferedImage, "jpg", imageFile);
    System.out.println(" end write image ");
}

From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java

private BufferedImage prepareImage(ImageInputStream pImageIn, int pHeight, int pWidth, VgElevationGrid pTerrain,
        double pPitch, double pYaw, double pDistance, double pExaggeration, boolean pDrawNorthArrow,
        boolean pHints) {
    BufferedImage lImage = null;//w  ww . j  a  v  a  2 s.c  om
    Iterator iter = ImageIO.getImageReaders(pImageIn); // liefert PNG-ImageReader
    ImageReader reader = (ImageReader) iter.next();
    reader.setInput(pImageIn, true); // seek forward only?

    boolean ready = false;
    int lMaxIntervalChecks = 40;
    long lCheckInterval = mRendererTimeout / lMaxIntervalChecks;
    int ct = 0;
    while ((!ready) && (ct < lMaxIntervalChecks)) {
        try {
            lImage = reader.read(0);
            ready = true;
        } catch (IOException e) {
            ct++;
            try {
                Thread.sleep(lCheckInterval);
            } catch (Exception e2) {
            }
            ;
        }
    }
    if (!ready)
        throw new T3dException("An I/O exception occured. The renderer did not generate an image file.", 403);

    // Copyright-Text und Nordpfeil ergnzen:
    this.addAnnotations(lImage, pHeight, pWidth, pPitch, pYaw, pDrawNorthArrow);
    // Ggf. weitere Information (Hints) ergnzen:
    if (pHints)
        this.addHints(lImage, pTerrain, pDistance, pYaw, pExaggeration);

    return lImage;
}

From source file:nl.b3p.viewer.image.ImageTool.java

/** Reads an image from an http input stream.
 *
 * @param method Apache HttpClient GetMethod object
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage/*from  ww  w. j a v a 2  s  .  c om*/
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(HttpMethod method, String mime) throws Exception {
    ImageReader ir = null;
    BufferedImage i = null;
    try {
        if (mime.indexOf(";") != -1) {
            mime = mime.substring(0, mime.indexOf(";"));
        }
        String mimeType = getMimeType(mime);

        /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de 
         * HttpClient vernieuwing in kaartenbalie ? */
        if (mimeType == null) {
            mimeType = "image/png";
        }

        if (mimeType == null) {
            log.error("Response from server not understood (mime = " + mime + "): "
                    + method.getResponseBodyAsString());
            throw new Exception("Response from server not understood (mime = " + mime + "): "
                    + method.getResponseBodyAsString());
        }

        ir = getReader(mimeType);
        if (ir == null) {
            log.error("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
            throw new Exception("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        }
        //TODO Make smarter.. Possibly faster... But keep reporting!
        InputStream is = method.getResponseBodyAsStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead = 0;
        byte[] buffer = new byte[2048];
        while (bytesRead != -1) {
            bytesRead = is.read(buffer, 0, buffer.length);
            if (bytesRead > 0) {
                baos.write(buffer, 0, bytesRead);
            }
        }
        ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
        ir.setInput(stream, true);
        i = ir.read(0);
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
    } finally {
        if (ir != null) {
            ir.dispose();
        }
    }
    return i;
}

From source file:com.moviejukebox.scanner.artwork.ArtworkScanner.java

/**
 * Get the size of the file at the end of the URL
 *
 * Taken from: http://forums.sun.com/thread.jspa?threadID=528155&messageID=2537096
 *
 * @param artworkImage Artwork image to check
 * @param artworkWidth The width to check
 * @param artworkHeight The height to check
 * @param checkAspect Should the aspect ratio be checked
 * @return True if the poster is good, false otherwise
 *//*  w w  w  .  j  a va2 s. c om*/
@Override
public boolean validateArtwork(IImage artworkImage, int artworkWidth, int artworkHeight, boolean checkAspect) {
    @SuppressWarnings("rawtypes")
    Iterator readers = ImageIO.getImageReadersBySuffix("jpeg");
    ImageReader reader = (ImageReader) readers.next();
    int urlWidth;
    int urlHeight;
    float urlAspect;

    if (!artworkValidate) {
        return Boolean.TRUE;
    }

    if (artworkImage.getUrl().equalsIgnoreCase(Movie.UNKNOWN)) {
        return Boolean.FALSE;
    }

    try (InputStream in = new URL(artworkImage.getUrl()).openStream();
            ImageInputStream iis = ImageIO.createImageInputStream(in)) {
        reader.setInput(iis, Boolean.TRUE);
        urlWidth = reader.getWidth(0);
        urlHeight = reader.getHeight(0);
    } catch (IOException ex) {
        LOG.debug("ValidateArtwork error: {}: can't open URL", ex.getMessage());
        return Boolean.FALSE; // Quit and return a Boolean.FALSE poster
    }

    urlAspect = (float) urlWidth / (float) urlHeight;

    if (checkAspect && urlAspect > 1.0) {
        LOG.debug("{} rejected: URL is wrong aspect (portrait/landscape)", artworkImage);
        return Boolean.FALSE;
    }

    // Adjust artwork width / height by the ValidateMatch figure
    int newArtworkWidth = artworkWidth * (artworkValidateMatch / 100);
    int newArtworkHeight = artworkHeight * (artworkValidateMatch / 100);

    if (urlWidth < newArtworkWidth) {
        LOG.debug("{} rejected: URL width ({}) is smaller than artwork width ({})", artworkImage, urlWidth,
                newArtworkWidth);
        return Boolean.FALSE;
    }

    if (urlHeight < newArtworkHeight) {
        LOG.debug("{} rejected: URL height ({}) is smaller than artwork height ({})", artworkImage, urlHeight,
                newArtworkHeight);
        return Boolean.FALSE;
    }
    return Boolean.TRUE;
}

From source file:lucee.runtime.img.Image.java

public IIOMetadata getMetaData(Struct parent) {
    InputStream is = null;/*from   w w w  .  j av  a2  s  .c om*/
    javax.imageio.stream.ImageInputStreamImpl iis = null;
    try {

        if (source instanceof File) {
            iis = new FileImageInputStream((File) source);
        } else if (source == null)
            iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true)));
        else
            iis = new MemoryCacheImageInputStream(is = source.getInputStream());

        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            // pick the first available ImageReader
            ImageReader reader = readers.next();
            IIOMetadata meta = null;
            synchronized (sync) {
                // attach source to the reader
                reader.setInput(iis, true);

                // read metadata of first image
                meta = reader.getImageMetadata(0);
                meta.setFromTree(FORMAT, meta.getAsTree(FORMAT));
                reader.reset();
            }
            // generating dump
            if (parent != null) {
                String[] formatNames = meta.getMetadataFormatNames();
                for (int i = 0; i < formatNames.length; i++) {
                    Node root = meta.getAsTree(formatNames[i]);
                    //print.out(XMLCaster.toString(root));
                    addMetaddata(parent, "metadata", root);
                }
            }
            return meta;
        }
    } catch (Throwable t) {
    } finally {
        ImageUtil.closeEL(iis);
        IOUtil.closeEL(is);
    }
    return null;
}