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:de.ailis.wlandsuite.PackPics.java

/**
 * @see de.ailis.wlandsuite.cli.PackProg#pack(java.io.File,
 *      java.io.OutputStream)//from  w  ww .ja v a 2 s  . c  om
 */

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

    picNo = 0;
    animations = new ArrayList<PicsAnimation>();
    while (true) {
        picDirectory = new File(
                String.format("%s%c%03d", new Object[] { directory.getPath(), File.separatorChar, picNo }));
        if (!picDirectory.exists()) {
            break;
        }

        log.info("Reading pic " + picNo);

        // Read the base frame
        baseFrame = new Pic(ImageIO.read(new File(picDirectory.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[] { picDirectory.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++;
        }
        animations.add(new PicsAnimation(baseFrame, frameSet));

        picNo++;
    }

    pics = new Pics(animations);
    if (this.disk == -1) {
        pics.write(output);
    } else {
        pics.write(output, this.disk);
    }
}

From source file:ScaleTest_2008.java

/**
 * Paints the test image that will be downscaled and timed by the various
 * scaling methods. A different image is rendered into each of the four
 * quadrants of this image: RGB stripes, a picture, vector art, and 
 * a black and white grid./*from   w  w w.  j  a  v  a  2s. co  m*/
 */
private void paintOriginalImage() {
    Graphics g = originalImage.getGraphics();
    // Erase to black
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, FULL_SIZE, FULL_SIZE);

    // RGB quadrant
    for (int i = 0; i < QUAD_SIZE; i += 3) {
        int x = i;
        g.setColor(Color.RED);
        g.drawLine(x, 0, x, QUAD_SIZE);
        x++;
        g.setColor(Color.GREEN);
        g.drawLine(x, 0, x, QUAD_SIZE);
        x++;
        g.setColor(Color.BLUE);
        g.drawLine(x, 0, x, QUAD_SIZE);
    }

    // Picture quadrant
    try {
        URL url = getClass().getResource("BBGrayscale.png");
        BufferedImage picture = ImageIO.read(url);
        // Center picture in quadrant area
        int xDiff = QUAD_SIZE - picture.getWidth();
        int yDiff = QUAD_SIZE - picture.getHeight();
        g.drawImage(picture, QUAD_SIZE + xDiff / 2, yDiff / 2, null);
    } catch (Exception e) {
        System.out.println("Problem reading image file: " + e);
    }

    // Vector drawing quadrant
    g.setColor(Color.WHITE);
    g.fillRect(0, QUAD_SIZE, QUAD_SIZE, QUAD_SIZE);
    g.setColor(Color.BLACK);
    g.drawOval(2, QUAD_SIZE + 2, QUAD_SIZE - 4, QUAD_SIZE - 4);
    g.drawArc(20, QUAD_SIZE + 20, (QUAD_SIZE - 40), QUAD_SIZE - 40, 190, 160);
    int eyeSize = 7;
    int eyePos = 30 - (eyeSize / 2);
    g.fillOval(eyePos, QUAD_SIZE + eyePos, eyeSize, eyeSize);
    g.fillOval(QUAD_SIZE - eyePos - eyeSize, QUAD_SIZE + eyePos, eyeSize, eyeSize);

    // B&W grid
    g.setColor(Color.WHITE);
    g.fillRect(QUAD_SIZE + 1, QUAD_SIZE + 1, QUAD_SIZE, QUAD_SIZE);
    g.setColor(Color.BLACK);
    for (int i = 0; i < QUAD_SIZE; i += 4) {
        int pos = QUAD_SIZE + i;
        g.drawLine(pos, QUAD_SIZE + 1, pos, FULL_SIZE);
        g.drawLine(QUAD_SIZE + 1, pos, FULL_SIZE, pos);
    }

    originalImagePainted = true;
}

From source file:com.skcraft.launcher.swing.InstanceTableModel.java

@Override
public Object getValueAt(final int rowIndex, final int columnIndex) {
    final Instance instance = instances.get(rowIndex);
    switch (columnIndex) {
    case 0:/*from ww w  .j  av a2  s.  com*/
        if (rowIndex == 0)
            return welcomeIcon;
        InstanceIcon instanceIcon = instanceIcons.get(rowIndex);
        if (instanceIcon == null) {
            // freshly-requested icon. First set some defaults
            Icon iconLocal = SwingHelper.createIcon(Launcher.class, "instance_icon.png", 96, 64);
            instanceIcon = new InstanceIcon();
            instanceIcon.setIconLocal(iconLocal);
            try {
                instanceIcon.setIconRemote(
                        buildDownloadIcon(ImageIO.read(Launcher.class.getResource("instance_icon.png"))));
            } catch (IOException e) {
                e.printStackTrace();
            }
            instanceIcons.put(rowIndex, instanceIcon);
        }
        final InstanceIcon instanceIconLoaded = instanceIcons.get(rowIndex);

        if (!instanceIcon.isLoaded()) {
            // attempt to load instance-specific icon
            instanceIconLoaded.setLoaded(true);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    String modpackUrlDir = FilenameUtils.getFullPath(instance.getManifestURL().toString());
                    URL instanceIconUrl = null;
                    try {
                        instanceIconUrl = new URL(modpackUrlDir + "icon.png");
                        //HttpURLConnection conn = (HttpURLConnection) instanceIconUrl.openConnection();
                        //conn.setDoOutput(false);
                        //BufferedImage downloadedIcon = ImageIO.read(conn.getInputStream());
                        BufferedImage downloadedIcon = ImageIO.read(instanceIconUrl);
                        instanceIconLoaded.setIconLocal(new ImageIcon(downloadedIcon));
                        instanceIconLoaded.setIconRemote(buildDownloadIcon(downloadedIcon));
                        fireTableDataChanged();
                    } catch (IOException e) {
                        log.warning("Could not download remote icon for instance '" + instance.getName()
                                + "' from " + instanceIconUrl.toString());
                    }
                }
            });
        }
        if (instance.isLocal()) {
            return instanceIcon.getIconLocal();
        } else {
            return instanceIcon.getIconRemote();
        }
    case 1:
        return instance.getTitle();
    default:
        return null;
    }
}

From source file:com.drcl.yz.web.UploadAction.java

/**
 * /*from w  w  w.  jav a  2s  .com*/
 * 
 * @return
 * @throws Exception
 */

@Override
public String execute() throws Exception {
    String date = DateFormatUtils.format(new Date(), "yyyyMM");
    String realPath = RequestUtils.getRealPath(ServletActionContext.getServletContext(), "/");

    // ?
    String localFilePath = realPath + Global.picpath + "/" + date;

    try {
        if (file != null) {
            fileName = "";
            List<String> fileTypes = Lists.newArrayList();
            fileTypes.add("jpg");
            fileTypes.add("gif");
            fileTypes.add("png");
            Image img = ImageIO.read(file);
            if (img == null) {
                message = "????";
                return SUCCESS;
            }

            message = FileUploadUtils.fileTypeValidate(fileFileName, file, fileTypes, 1024);

            if (message == null) {
                fileName = FileUtils.saveFile(localFilePath, file, fileFileName, "im");
                fileName = "/" + date + "/" + fileName;
                message = "?";

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        message = "?,!";
    }

    return SUCCESS;
}

From source file:com.seleniumtests.util.FileUtility.java

/**
 * Constructs ImageElement from bytes and stores it.
 *
 * @param  path/*  www.  j  ava  2s.  c o m*/
 */
public static synchronized void writeImage(final String path, final byte[] byteArray) {
    if (byteArray.length == 0) {
        return;
    }

    byte[] decodeBuffer = Base64.decodeBase64(byteArray);

    try (InputStream in = new ByteArrayInputStream(decodeBuffer)) {
        BufferedImage img = ImageIO.read(in);
        writeImage(path, img);
    } catch (Exception e) {
        logger.warn(e);
    }

}

From source file:org.nekorp.workflow.desktop.servicio.imp.ImageServiceImp.java

public BufferedImage getImageFromBase64(String image) {
    try {//from   w w w.  j  a  va 2s  .  c  o m
        Base64 util = new Base64();
        BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(util.decode(image)));
        return bufImg;
    } catch (IOException ex) {
        throw new IllegalArgumentException("error al convertir a imagen desde string en base 64", ex);
    }
}

From source file:com.joliciel.jochre.doc.ImageDocumentExtractorImpl.java

@Override
public JochreDocument extractDocument() {
    LOG.debug("ImageDocumentExtractorImpl.extractDocument");
    try {//from   ww  w.  ja  va 2  s  .  c  o m
        File[] files = new File[1];

        if (imageFile.isDirectory()) {
            files = imageFile.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    return (name.toLowerCase().endsWith(".png") || name.toLowerCase().endsWith(".jpg")
                            || name.toLowerCase().endsWith(".jpeg") || name.toLowerCase().endsWith(".gif"));
                }
            });
        } else {
            files[0] = imageFile;
        }

        JochreDocument doc = this.documentProcessor.onDocumentStart();
        doc.setTotalPageCount(files.length);

        int currentPageNumber = this.pageNumber;
        for (File file : files) {
            JochrePage page = this.documentProcessor.onPageStart(currentPageNumber++);

            BufferedImage image = ImageIO.read(file);
            String imageName = file.getName();

            if (currentMonitor != null && documentProcessor instanceof Monitorable) {
                ProgressMonitor monitor = ((Monitorable) documentProcessor).monitorTask();
                double percentAllotted = (1 / (double) (files.length));
                currentMonitor.startTask(monitor, percentAllotted);
            }

            documentProcessor.onImageFound(page, image, imageName, 0);
            if (currentMonitor != null && documentProcessor instanceof Monitorable) {
                currentMonitor.endTask();
            }

            this.documentProcessor.onPageComplete(page);
        }
        this.documentProcessor.onDocumentComplete(doc);

        if (currentMonitor != null)
            currentMonitor.setFinished(true);
        return doc;
    } catch (Exception e) {
        LOG.debug("Exception occurred. Have monitor? " + currentMonitor);
        if (currentMonitor != null)
            currentMonitor.setException(e);
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } finally {
        LOG.debug("Exit ImageDocumentExtractorImpl.extractDocument");
    }
}

From source file:de.ppi.selenium.util.ScreenshotUtils.java

/***
 * You can use this method to take your control pictures. Note that the file
 * should be a png.//from   w  ww.ja v  a2 s  .  c  o  m
 *
 * @param element the webelement
 * @param toSaveAs the file where the screenshot should be save.
 * @param wd the webdriver.
 * @throws IOException if something goes wrong writing the result.
 */
public static void takeScreenshotOfElement(WebElement element, File toSaveAs, WebDriver wd) throws IOException {

    for (int i = 0; i < MAXIMAL_NR_OF_RETRIES; i++) { // Loop up to 10x to
                                                      // ensure a clean
                                                      // screenshot was taken
        LOG.info("Taking screen shot of locator " + element + " ... attempt #" + (i + 1));

        // Scroll to element
        // TODO Improvement element.scrollTo();

        // Take picture of the page
        File screenshot;
        boolean isRemote = false;
        if (!(wd instanceof RemoteWebDriver)) {
            screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);
        } else {
            Augmenter augmenter = new Augmenter();
            screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE);
            isRemote = true;
        }
        BufferedImage fullImage = ImageIO.read(screenshot);

        // Parse out the picture of the element
        Point point = element.getLocation();
        int eleWidth = element.getSize().getWidth();
        int eleHeight = element.getSize().getHeight();
        int x;
        int y;
        if (isRemote) {
            x = ((Locatable) element).getCoordinates().inViewPort().getX();
            y = ((Locatable) element).getCoordinates().inViewPort().getY();
        } else {
            x = point.getX();
            y = point.getY();
        }
        LOG.debug("Screenshot coordinates x: " + x + ", y: " + y);
        BufferedImage eleScreenshot = fullImage.getSubimage(x, y, eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);

        // Ensure clean snapshot (sometimes WebDriver takes bad pictures and
        // they turn out all black)
        if (!isBlack(ImageIO.read(screenshot))) {
            FileUtils.copyFile(screenshot, toSaveAs);
            break;
        }
    }
}

From source file:com.lingxiang2014.util.ImageUtils.java

public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);// w ww.  j a v  a  2s.c  om
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
        Graphics2D graphics2D = null;
        ImageOutputStream imageOutputStream = null;
        ImageWriter imageWriter = null;
        try {
            BufferedImage srcBufferedImage = ImageIO.read(srcFile);
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            int width = destWidth;
            int height = destHeight;
            if (srcHeight >= srcWidth) {
                width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight,
                    BufferedImage.TYPE_INT_RGB);
            graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(BACKGROUND_COLOR);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    (destWidth / 2) - (width / 2), (destHeight / 2) - (height / 2), null);

            imageOutputStream = ImageIO.createImageOutputStream(destFile);
            imageWriter = ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                    .next();
            imageWriter.setOutput(imageOutputStream);
            ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
            imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
            imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
            imageOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (graphics2D != null) {
                graphics2D.dispose();
            }
            if (imageWriter != null) {
                imageWriter.dispose();
            }
            if (imageOutputStream != null) {
                try {
                    imageOutputStream.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        IMOperation operation = new IMOperation();
        operation.thumbnail(destWidth, destHeight);
        operation.gravity("center");
        operation.background(toHexEncoding(BACKGROUND_COLOR));
        operation.extent(destWidth, destHeight);
        operation.quality((double) DEST_QUALITY);
        operation.addImage(srcFile.getPath());
        operation.addImage(destFile.getPath());
        if (type == Type.graphicsMagick) {
            ConvertCmd convertCmd = new ConvertCmd(true);
            if (graphicsMagickPath != null) {
                convertCmd.setSearchPath(graphicsMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        } else {
            ConvertCmd convertCmd = new ConvertCmd(false);
            if (imageMagickPath != null) {
                convertCmd.setSearchPath(imageMagickPath);
            }
            try {
                convertCmd.run(operation);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IM4JavaException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.flexive.shared.media.impl.FxMediaNativeEngine.java

/**
 * Scale an image and return the dimensions (width and height) as int array
 *
 * @param original  original file/*  www.ja  v a  2  s  . co  m*/
 * @param scaled    scaled file
 * @param extension extension
 * @param width     desired width
 * @param height    desired height
 * @return actual width ([0]) and height ([1]) of scaled image
 * @throws FxApplicationException on errors
 */
public static int[] scale(File original, File scaled, String extension, int width, int height)
        throws FxApplicationException {
    if (HEADLESS && FxMediaImageMagickEngine.IM_AVAILABLE && ".GIF".equals(extension)) {
        //native headless engine can't handle gif transparency ... so if we have IM we use it, else
        //transparent pixels will be black
        return FxMediaImageMagickEngine.scale(original, scaled, extension, width, height);
    }
    BufferedImage bi;
    try {
        bi = ImageIO.read(original);
    } catch (Exception e) {
        LOG.info("Failed to read " + original.getName() + " using ImageIO, trying sanselan");
        try {
            bi = Sanselan.getBufferedImage(original);
        } catch (Exception e1) {
            throw new FxApplicationException(LOG, "ex.media.readFallback.error", original.getName(), extension,
                    e.getMessage(), e1.getMessage());
        }
    }
    BufferedImage bi2 = scale(bi, width, height);

    String eMsg;
    boolean fallback;
    try {
        fallback = !ImageIO.write(bi2, extension.substring(1), scaled);
        eMsg = "No ImageIO writer found.";
    } catch (Exception e) {
        eMsg = e.getMessage();
        fallback = true;
    }
    if (fallback) {
        try {
            Sanselan.writeImage(bi2, scaled, getImageFormatByExtension(extension), new HashMap());
        } catch (Exception e1) {
            throw new FxApplicationException(LOG, "ex.media.write.error", scaled.getName(), extension,
                    eMsg + ", " + e1.getMessage());
        }
    }
    return new int[] { bi2.getWidth(), bi2.getHeight() };
}