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:AkashApplications.src.GenerateBarcode.java

public static BufferedImage decodeToImage(String imageString) {

    BufferedImage image = null;/*w w w  . j a v  a 2 s  .  c om*/
    byte[] imageByte;
    try {
        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}

From source file:com.comcast.video.dawg.show.video.BufferedImageCerealizer.java

/**
 * {@inheritDoc}// w w w  . j  av a  2s.  c  o m
 */
@Override
public BufferedImage deCerealize(String cereal, ObjectCache objectCache) throws CerealException {
    byte[] data = Base64.decodeBase64(cereal);
    ByteArrayInputStream bais = new ByteArrayInputStream(data);
    try {
        try {
            return ImageIO.read(bais);
        } catch (IOException e) {
            throw new CerealException("Failed to deCerealize BufferedImage", e);
        }
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:com.oneis.utils.ImageColouring.java

/**
 * Transform the colours in an image.//from   w  w w  . j a v a2s. com
 *
 * @param Filename Full pathname to the source file
 * @param Method Which colouring method to use, use METHOD_* constants
 * @param Colours Array of 0xRRGGBB colours for recolouring
 * @param JPEGQuality If the image is a JPEG, the output quality for
 * reencoding
 * @param Output An OutputStream to write the file. Will be closed.
 */
static public void colourImage(String Filename, int Method, int[] Colours, int JPEGQuality, OutputStream Output)
        throws IOException {
    ColouringInfo colouringInfo = prepareForColouring(Method, Colours);

    String extension = Filename.substring(Filename.lastIndexOf('.') + 1, Filename.length());
    String outputFormat = extension;

    if (outputFormat.equals("gif")) {
        if (!colourImageGIF(Filename, colouringInfo, Output)) {
            throw new RuntimeException("Failed to directly colour GIF file");
        }
        return;
    }

    BufferedImage image = ImageIO.read(new File(Filename));
    int width = image.getWidth();
    int height = image.getHeight();

    // Rewrite the pixels
    int[] pixelBuffer = new int[width];
    for (int y = 0; y < height; ++y) {
        image.getRGB(0, y, width, 1, pixelBuffer, 0, width);
        doColouring(pixelBuffer, colouringInfo);
        image.setRGB(0, y, width, 1, pixelBuffer, 0, width);
    }

    // Writing is done the hard way to enable the JPEG quality to be set.
    // Get a writer
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(outputFormat);
    if (!iter.hasNext()) {
        throw new RuntimeException("Couldn't write image of type " + outputFormat);
    }

    ImageWriter writer = iter.next();

    ImageWriteParam iwparam = null;

    // Is it JPEG? If so, might want to set the quality
    if (outputFormat.equals("jpeg") || outputFormat.equals("jpg")) {
        // Clamp value
        int q = JPEGQuality;
        if (q < 10) {
            q = 10;
        }
        if (q > 100) {
            q = 100;
        }

        JPEGImageWriteParam jparam = new JPEGImageWriteParam(null);
        jparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        jparam.setCompressionQuality((float) (((float) q) / 100.0));
        iwparam = jparam;
    }

    ImageOutputStream output = ImageIO.createImageOutputStream(Output);
    writer.setOutput(output);
    writer.write(null, new IIOImage(image, null, null), iwparam);

    output.close();
}

From source file:Main.java

/**
 * Loads an image from within a jar or from the file system.
 * /* w  w w .j av  a2 s .c o  m*/
 * @param fileName the image path. 
 * @param packageClass a class within the package where the image can be found
 * @return an initialised image-icon or null, when no image could be found.
 */
public static Image loadIcon(String fileName, Class packageClass) {
    try {
        ClassLoader classLoader = packageClass.getClassLoader();
        InputStream is = classLoader.getResourceAsStream(fileName);
        if (is == null) {
            File file = new File(fileName);
            if (file.exists()) {
                is = new FileInputStream(file);
            } else {
                return null;
            }
        }
        return ImageIO.read(is);
    } catch (IOException e) {
        System.err.println("Unable to load image [" + fileName + "]");
        e.printStackTrace();
        return null;
    }
}

From source file:org.jrecruiter.service.GoogleMapsStaticTest.java

private void sendGetRequest() {

    // Send a GET request to the servlet
    try {/*w  ww. ja  v a 2  s  .c o m*/

        final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(BigDecimal.TEN, BigDecimal.TEN, 10);
        final URLConnection conn = url.toURL().openConnection();

        final BufferedImage img = ImageIO.read(conn.getInputStream());

        Assert.assertNotNull(img);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.wudaosoft.net.httpclient.ImageResponseHandler.java

@Override
public BufferedImage handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();

    if (status != 200) {
        throw new ClientProtocolException("Unexpected response status: " + status);
    }//from  w  w  w .ja  v a 2  s  . c  om

    HttpEntity entity = response.getEntity();

    if (entity == null || !entity.isStreaming()) {
        throw new ClientProtocolException("Response contains no content");
    }

    BufferedImage buffImg = ImageIO.read(entity.getContent());
    return buffImg;
}

From source file:com.cognifide.aet.job.common.comparators.layout.utils.ImageComparisonConvertImageTest.java

@Test
public void convertImageTo2DArray_2x1Image_expectFirstPixelSame() throws Exception {
    try {/*from w  w w  .ja  va  2  s  .c  o  m*/
        // given
        patternStream = getClass().getResourceAsStream("/mock/LayoutComparator/comparingColors/2x1-red.png");
        BufferedImage pattern = ImageIO.read(patternStream);
        sampleStream = getClass()
                .getResourceAsStream("/mock/LayoutComparator/comparingColors/2x1-red-black.png");
        BufferedImage sample = ImageIO.read(sampleStream);
        // when
        int[][] patternPixels = ImageComparison.convertImageTo2DArray(pattern);
        int[][] samplePixels = ImageComparison.convertImageTo2DArray(sample);
        // then
        int patternPixel = patternPixels[0][0];
        int samplePixel = samplePixels[0][0];
        assertThat(patternPixel, is(equalTo(samplePixel)));
    } finally {
        closeInputStreams(imageStreams);
    }
}

From source file:org.dineth.shooter.app.view.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody/*www  .j av a  2s . c o  m*/
public String handleFormUpload(@RequestParam("file") MultipartFile file) {

    File destination = null;
    if (!file.isEmpty()) {

        try {
            BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));

            destination = new File(homefilefolder + file.getOriginalFilename());
            destination.mkdirs();

            ImageIO.write(src, FilenameUtils.getExtension(file.getOriginalFilename()), destination);

            //Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID.
        } catch (IOException ex) {
            Logger.getLogger(ImageController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        return "bad thing";
    }
    return destination.getName();
}

From source file:br.com.pontocontrol.controleponto.ExtObject.java

protected static Image getFileImageResource(String res) {
    try {//from ww  w. ja v  a  2 s .  co m
        final File file = getFileResource(projectImagesPath(), res);
        return ImageIO.read(file);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, "Erro ao ler cone para janela e barra de tarefas.", ex);
        return null;
    }
}

From source file:com.haulmont.cuba.desktop.DesktopResources.java

public Image getImage(String name) {
    byte[] bytes = getImageBytes(name);

    try {//from   ww w .java  2  s.  c  o m
        return ImageIO.read(new ByteArrayInputStream(bytes));
    } catch (IOException e) {
        log.warn("Unable to read image from bytes", e);
        return null;
    }
}