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:apiserver.services.images.services.coldfusion.ImageResizeCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    FileResizeJob props = (FileResizeJob) message.getPayload();

    try {//from   w w w  .j  a  va 2s.  c  o  m
        cfcPath = imageConfigMBean.getImageResizePath();
        String method = imageConfigMBean.getImageResizeMethod();
        String arguments = "";
        // extract properties
        Map<String, Object> methodArgs = props.toMap();

        // execute
        Object cfcResult = coldFusionBridge.invoke(cfcPath, method, methodArgs);

        if (cfcResult instanceof byte[]) {
            // convert base64 back to buffered image
            byte[] bytes = Base64.decodeBase64(new String((byte[]) cfcResult));
            BufferedImage bi = ImageIO.read(new ByteArrayInputStream(bytes));
            props.setBufferedImage(bi);
        } else {
            throw new NotImplementedException();
        }

        return props;

    } catch (Throwable e) {
        e.printStackTrace(); //todo use logging library
        throw new RuntimeException(e);
    } finally {

    }
}

From source file:org.jrecruiter.service.impl.DataServiceImpl.java

/** {@inheritDoc} */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Image getGoogleMapImage(final BigDecimal latitude, final BigDecimal longitude, final Integer zoomLevel) {

    if (longitude == null) {
        throw new IllegalArgumentException("Longitude cannot be null.");
    }/* w  w  w.ja  va  2  s.c o m*/

    if (latitude == null) {
        throw new IllegalArgumentException("Latitude cannot be null.");
    }

    if (zoomLevel == null) {
        throw new IllegalArgumentException("ZoomLevel cannot be null.");
    }

    final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(latitude, longitude, zoomLevel);

    BufferedImage img;
    try {
        URLConnection conn = url.toURL().openConnection();
        img = ImageIO.read(conn.getInputStream());
    } catch (UnknownHostException e) {
        LOGGER.error("Google static MAPS web service is not reachable (UnknownHostException).", e);
        img = new BufferedImage(GoogleMapsUtils.defaultWidth, 100, BufferedImage.TYPE_INT_RGB);

        final Graphics2D graphics = img.createGraphics();

        final Map<Object, Object> renderingHints = CollectionUtils.getHashMap();
        renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.addRenderingHints(renderingHints);
        graphics.setBackground(Color.WHITE);
        graphics.setColor(Color.GRAY);
        graphics.clearRect(0, 0, GoogleMapsUtils.defaultWidth, 100);

        graphics.drawString("Not Available", 30, 30);

    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    return img;
}

From source file:dotaSoundEditor.Helpers.PortraitFinder.java

private void buildHeroPortraits(VPKArchive vpk) {

    BufferedImage image = null;//from  w  ww.  j a  v a  2s .  c o  m
    for (VPKEntry entry : vpk.getEntriesForDir("resource/flash3/images/heroes/")) {
        if (entry.getType().equals("png") && !(entry.getPath().contains("selection"))) {
            File imageFile = new File(entry.getPath());

            try (FileChannel fc = FileUtils.openOutputStream(imageFile).getChannel()) {
                fc.write(entry.getData());
                image = ImageIO.read(imageFile);
                portraitMap.put(entry.getName(), image);
            } catch (IOException ex) {
                System.err.println("Can't write " + entry.getPath() + ": " + ex.getMessage());
            }
        }
    }
}

From source file:de.ailis.wlandsuite.PackCpa.java

/**
 * @see de.ailis.wlandsuite.cli.PackProg#pack(java.io.File,
 *      java.io.OutputStream)/*from   www .ja va2s .c o  m*/
 */

@Override
protected void pack(File directory, OutputStream output) throws IOException {
    Cpa cpa;
    Pic baseFrame;
    Pic pic;
    List<CpaFrame> frames;
    int frameNo;
    File frameFile;
    BufferedReader reader;
    String line;
    List<Integer> delays;
    int delay;
    File file;

    // Read the base frame
    file = new File(directory.getPath() + File.separatorChar + "000.png");
    if (!file.exists()) {
        log.error("Base frame PNG '" + file.getPath() + "' not found");
    }
    baseFrame = new Pic(ImageIO.read(file));

    // Read the animation delays
    delays = new ArrayList<Integer>();
    file = new File(directory.getPath() + File.separatorChar + "delays.txt");
    if (file.exists()) {
        reader = new BufferedReader(new FileReader(file));
        try {
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.length() == 0 || line.startsWith("#")) {
                    continue;
                }
                delays.add(Integer.valueOf(line));
            }
        } finally {
            reader.close();
        }
    } else {
        log.warn("Delays file '" + file.getPath() + "' not found");
    }

    // Read the animation frames
    frames = new ArrayList<CpaFrame>();
    frameNo = 1;
    while (true) {
        frameFile = new File(String.format("%s%c%03d.png",
                new Object[] { directory.getPath(), File.separatorChar, frameNo }));
        if (!frameFile.exists()) {
            break;
        }
        pic = new Pic(ImageIO.read(frameFile));
        if (frameNo > delays.size()) {
            log.warn("No delay found for frame " + frameNo + ". Using default delay 2");
            delay = 2;
        } else {
            delay = delays.get(frameNo - 1);
        }
        frames.add(new CpaFrame(delay, pic));
        frameNo++;
    }
    if (frameNo != 16) {
        log.warn("Wasteland needs 15 animation frames. But " + (frameNo - 1)
                + " frames were found. This may cause trouble.");
    }

    cpa = new Cpa(baseFrame, frames);
    cpa.write(output);
}

From source file:de.ailis.wlandsuite.PackPic.java

/**
 * @see de.ailis.wlandsuite.cli.PackProg#pack(java.io.File,
 *      java.io.OutputStream)/*  w w w .  j  a v a2s  . co m*/
 */

@Override
public void pack(File directory, OutputStream output) throws IOException {
    List<PicsAnimationFrameSet> frameSet;
    List<PicsAnimationInstruction> instructions;
    List<Pic> frames;
    Pic baseFrame, frame;
    String line;
    String[] parts;
    int delay;
    int frameSetNo, frameNo;
    BufferedReader reader;
    File file;
    File setDirectory;
    int lineNo;

    // Read the base frame
    baseFrame = new Pic(ImageIO.read(new File(directory.getPath() + File.separatorChar + "000.png")));

    // Read the frame sets
    frameSetNo = 0;
    frameSet = new ArrayList<PicsAnimationFrameSet>();
    while (true) {
        setDirectory = new File(String.format("%s%c%03d",
                new Object[] { directory.getPath(), File.separatorChar, frameSetNo }));
        if (!setDirectory.exists()) {
            break;
        }

        // Read the instructions
        instructions = new ArrayList<PicsAnimationInstruction>();
        file = new File(setDirectory.getPath() + File.separatorChar + "animation.txt");
        if (!file.exists()) {
            log.error("Animation file '" + file.getPath() + "' not found");
        }
        reader = new BufferedReader(new FileReader(file));
        lineNo = 0;
        while ((line = reader.readLine()) != null) {
            lineNo++;
            line = line.split("#")[0].trim();
            if (line.length() == 0)
                continue;
            parts = line.split("[ \\t]+");
            try {
                delay = Integer.parseInt(parts[0]);
                frameNo = Integer.parseInt(parts[1]);
                instructions.add(new PicsAnimationInstruction(delay, frameNo));
            } catch (Exception e) {
                log.error("Syntax error in animation file '" + file.getPath() + "' line " + lineNo);
            }
        }

        // Read the frames
        frameNo = 0;
        frames = new ArrayList<Pic>();
        while (true) {
            file = new File(String.format("%s%c%03d.png",
                    new Object[] { setDirectory.getPath(), File.separatorChar, frameNo + 1 }));
            if (!file.exists()) {
                break;
            }
            frame = new Pic(ImageIO.read(file));
            frames.add(frame);

            frameNo++;
        }
        frameSet.add(new PicsAnimationFrameSet(frames, instructions));
        frameSetNo++;
    }

    new PicsAnimation(baseFrame, frameSet).writeHacked(output);
}

From source file:com.github.cmisbox.ui.UI.java

private UI() {
    this.log = LogFactory.getLog(this.getClass());
    try {//  w  ww  .j a  v  a 2  s . c  om
        this.available = !GraphicsEnvironment.isHeadless();

        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

        if (SystemTray.isSupported()) {

            this.tray = SystemTray.getSystemTray();
            Image image = ImageIO.read(this.getClass().getResource("images/cmisbox.png"));

            ActionListener exitListener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Main.exit(0);
                }
            };

            this.popup = new PopupMenu();
            MenuItem defaultItem = new MenuItem(Messages.exit);
            defaultItem.addActionListener(exitListener);
            this.popup.add(defaultItem);

            MenuItem loginItem = new MenuItem(Messages.login);
            loginItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    new LoginDialog();
                }
            });
            this.popup.add(loginItem);

            MenuItem treeItem = new MenuItem(Messages.showTree);
            treeItem.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    new TreeSelect();
                }
            });

            this.popup.add(treeItem);

            final TrayIcon trayIcon = new TrayIcon(image, UI.NOTIFY_TITLE, this.popup);

            trayIcon.setImageAutoSize(true);

            this.tray.add(trayIcon);

            this.notify(Messages.startupComplete);

        }

    } catch (Exception e) {
        this.log.error(e);
    }
}

From source file:ImageUtil.java

public static ByteArrayOutputStream scale(ByteArrayInputStream bais, int width, int height) throws IOException {
    BufferedImage src = ImageIO.read(bais);
    BufferedImage dest = scale(src, width, height);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(dest, "JPG", baos);
    return baos;//from  www  .  jav  a2  s.co m
}

From source file:com.silverpeas.util.ImageUtil.java

public static String[] getWidthAndHeightByWidth(InputStream image, int widthParam) {
    String[] result = new String[2];
    try {/*from   w  w  w.java  2s  .  com*/
        BufferedImage inputBuf = ImageIO.read(image);
        // calcul de la taille de la sortie
        double inputBufWidth;
        double inputBufHeight;
        double width;
        double ratio;
        double height;
        if (inputBuf.getWidth() > widthParam) {
            inputBufWidth = inputBuf.getWidth();
            inputBufHeight = inputBuf.getHeight();
            width = widthParam;
            ratio = inputBufWidth / width;
            height = inputBufHeight / ratio;
        } else {
            width = inputBuf.getWidth();
            height = inputBuf.getHeight();
        }
        String sWidth = Double.toString(width);
        String sHeight = Double.toString(height);

        result[0] = sWidth.substring(0, sWidth.indexOf('.'));
        result[1] = sHeight.substring(0, sHeight.indexOf('.'));

        return result;
    } catch (Exception e) {
        if (image != null) {
            SilverTrace.error("util", "ImageUtil.getWidthAndHeightByWidth", "root.MSG_GEN_ERROR", e);
        }
    }
    result[0] = "";
    result[1] = "";
    return result;
}

From source file:com.reydentx.core.common.PhotoUtils.java

public static byte[] resizeImageScaleCrop(InputStream data, int img_width, int img_height, boolean isPNG) {
    BufferedImage originalImage;//  w ww  .  j a va2 s .c om
    try {
        originalImage = ImageIO.read(data);
        Dimension origDimentsion = new Dimension(originalImage.getWidth(), originalImage.getHeight());
        Dimension fitDimentsion = new Dimension(img_width, img_height);

        int flag = testThresholdMinWidthHeightImage(origDimentsion, fitDimentsion);
        // size Anh dang: MinW < W < 720, MinH < H < 720.
        if (flag == -1) {
            data.reset();
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
            byte[] read = new byte[2048];
            int i = 0;
            while ((i = data.read(read)) > 0) {
                byteArray.write(read, 0, i);
            }
            data.close();
            return byteArray.toByteArray();
        } else if (flag == 0) {
            // size Anh dang: MinW < W < 720 < H || MinH < H < 720 < W
            double ratioWidth = (origDimentsion.width * 1.0) / fitDimentsion.width;
            double ratioHeight = (origDimentsion.height * 1.0) / fitDimentsion.height;
            if (ratioWidth < ratioHeight) {
                // fit width, crop height image.
                int yH = 0;
                if (origDimentsion.height > fitDimentsion.height) {
                    yH = (origDimentsion.height - fitDimentsion.height) / 2;
                }
                return cropBufferedImage(isPNG, originalImage, 0, yH, origDimentsion.width,
                        fitDimentsion.height);
            } else {
                // fit height, crop width image.
                int xW = 0;
                if (origDimentsion.width > fitDimentsion.width) {
                    xW = (origDimentsion.width - fitDimentsion.width) / 2;
                }
                return cropBufferedImage(isPNG, originalImage, xW, 0, fitDimentsion.width,
                        origDimentsion.height);
            }
        } else {
            // size Anh dang: 720 < W,H.
            // Scale Image.
            double ratioWidth = (origDimentsion.width * 1.0) / fitDimentsion.width;
            double ratioHeight = (origDimentsion.height * 1.0) / fitDimentsion.height;
            if (ratioWidth < ratioHeight) {
                // fit width, crop height image.
                int new_width = fitDimentsion.width;
                int new_height = (int) (origDimentsion.height / ratioWidth);
                int yH = 0;
                if (new_height > fitDimentsion.height) {
                    yH = (new_height - fitDimentsion.height) / 2;
                }

                byte[] scaleByteImage = scaleBufferedImage(isPNG, originalImage, 0, 0, new_width, new_height);
                if (scaleByteImage != null && scaleByteImage.length > 0) {
                    InputStream isImg = new ByteArrayInputStream(scaleByteImage);
                    BufferedImage scaleBufferedImage = ImageIO.read(isImg);

                    // Crop width image.
                    return cropBufferedImage(isPNG, scaleBufferedImage, 0, yH, fitDimentsion.width,
                            fitDimentsion.height);
                }
            } else {
                // fit height, crop width image.
                int new_width = (int) (origDimentsion.width / ratioHeight);
                int new_height = fitDimentsion.height;
                int xW = 0;
                if (new_width > fitDimentsion.width) {
                    xW = (new_width - fitDimentsion.width) / 2;
                }

                byte[] scaleByteImage = scaleBufferedImage(isPNG, originalImage, 0, 0, new_width, new_height);
                if (scaleByteImage != null && scaleByteImage.length > 0) {
                    InputStream isImg = new ByteArrayInputStream(scaleByteImage);
                    BufferedImage scaleBufferedImage = ImageIO.read(isImg);

                    // Crop height image.
                    return cropBufferedImage(isPNG, scaleBufferedImage, xW, 0, fitDimentsion.width,
                            fitDimentsion.height);
                }
            }
        }
    } catch (Exception ex) {
    }
    return null;
}

From source file:com.sonicle.webtop.contacts.rpt.RptAddressbook.java

@Override
protected void fillBuiltInParams() {
    super.fillBuiltInParams();

    String pkgName = LangUtils.getClassPackageName(this.getClass());
    String basepath = LangUtils.packageToPath(pkgName);
    ClassLoader cl = LangUtils.findClassLoader(this.getClass());

    InputStream is = null;//w w w .j  a  va  2s  . c  o  m
    try {
        is = cl.getResourceAsStream(basepath + "/img-contact.png");
        params.put("CONTACT_IMAGE", ImageIO.read(is));
    } catch (IOException ex) {
        throw new WTRuntimeException("Unable to read image", ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
    try {
        is = cl.getResourceAsStream(basepath + "/img-contacts-list.png");
        params.put("CONTACTS_LIST_IMAGE", ImageIO.read(is));
    } catch (IOException ex) {
        throw new WTRuntimeException("Unable to read image", ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}