Search in sources :

Example 1 with ImageReader

use of javax.imageio.ImageReader in project AozoraEpub3 by hmdev.

the class ImageInfo method getImageInfo.

/** 画像ストリームから画像情報を生成
	 * @param zipIndex Zipファイルの場合はエントリの位置 (再読込や読み飛ばし時のファイル名比較の省略用)
	 * @throws IOException */
public static ImageInfo getImageInfo(InputStream is, int zipIndex) throws IOException {
    ImageInfo imageInfo = null;
    ImageInputStream iis = ImageIO.createImageInputStream(is);
    Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
    if (readers.hasNext()) {
        ImageReader reader = readers.next();
        if (readers.hasNext() && reader.getClass().getName().endsWith("CLibPNGImageReader"))
            readers.next();
        reader.setInput(iis);
        String ext = reader.getFormatName();
        imageInfo = new ImageInfo(ext, reader.getWidth(0), reader.getHeight(0), zipIndex);
        reader.dispose();
    }
    return imageInfo;
}
Also used : ImageInputStream(javax.imageio.stream.ImageInputStream) ImageReader(javax.imageio.ImageReader)

Example 2 with ImageReader

use of javax.imageio.ImageReader in project openhab1-addons by openhab.

the class Telegram method sendTelegramPhoto.

@ActionDoc(text = "Sends a Picture, protected by username/password authentication, via Telegram REST API")
public static boolean sendTelegramPhoto(@ParamDoc(name = "group") String group, @ParamDoc(name = "photoURL") String photoURL, @ParamDoc(name = "caption") String caption, @ParamDoc(name = "username") String username, @ParamDoc(name = "password") String password) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    if (photoURL == null) {
        logger.error("photoURL not defined, action skipped");
        return false;
    }
    // load image from url
    byte[] imageFromURL;
    HttpClient getClient = new HttpClient();
    if (username != null && password != null) {
        getClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        getClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    }
    GetMethod getMethod = new GetMethod(photoURL);
    getMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
        int statusCode = getClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", getMethod.getStatusLine());
            return false;
        }
        imageFromURL = getMethod.getResponseBody();
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        getMethod.releaseConnection();
    }
    // parse image type
    String imageType;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageFromURL));
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
        if (!imageReaders.hasNext()) {
            logger.error("photoURL does not represent a known image type");
            return false;
        }
        ImageReader reader = imageReaders.next();
        imageType = reader.getFormatName();
    } catch (IOException e) {
        logger.error("cannot parse photoURL as image: {}", e.getMessage());
        return false;
    }
    // post photo to telegram
    String url = String.format(TELEGRAM_PHOTO_URL, groupTokens.get(group).getToken());
    PostMethod postMethod = new PostMethod(url);
    try {
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        Part[] parts = new Part[caption != null ? 3 : 2];
        parts[0] = new StringPart("chat_id", groupTokens.get(group).getChatId());
        parts[1] = new FilePart("photo", new ByteArrayPartSource(String.format("image.%s", imageType), imageFromURL));
        if (caption != null) {
            parts[2] = new StringPart("caption", caption, "UTF-8");
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) ImageInputStream(javax.imageio.stream.ImageInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ByteArrayInputStream(java.io.ByteArrayInputStream) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) ImageReader(javax.imageio.ImageReader) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 3 with ImageReader

use of javax.imageio.ImageReader in project nutz by nutzam.

the class Images method readJpeg.

/**
     * 尝试读取JPEG文件的高级方法,可读取32位的jpeg文件
     * <p/>
     * 来自:
     * http://stackoverflow.com/questions/2408613/problem-reading-jpeg-image-
     * using-imageio-readfile-file
     * 
     */
private static BufferedImage readJpeg(InputStream in) throws IOException {
    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
    ImageReader reader = null;
    while (readers.hasNext()) {
        reader = readers.next();
        if (reader.canReadRaster()) {
            break;
        }
    }
    if (reader == null)
        return null;
    ImageInputStream input = ImageIO.createImageInputStream(in);
    reader.setInput(input);
    // Read the image raster
    Raster raster = reader.readRaster(0, null);
    BufferedImage image = createJPEG4(raster);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    writeJpeg(image, out, 1);
    out.flush();
    return read(new ByteArrayInputStream(out.toByteArray()));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) Raster(java.awt.image.Raster) WritableRaster(java.awt.image.WritableRaster) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage)

Example 4 with ImageReader

use of javax.imageio.ImageReader in project twitter-2-weibo by rjyo.

the class ImageItem method getContentType.

public static String getContentType(byte[] mapObj) throws IOException {
    String type = "";
    ByteArrayInputStream bais = null;
    MemoryCacheImageInputStream mcis = null;
    try {
        bais = new ByteArrayInputStream(mapObj);
        mcis = new MemoryCacheImageInputStream(bais);
        Iterator itr = ImageIO.getImageReaders(mcis);
        while (itr.hasNext()) {
            ImageReader reader = (ImageReader) itr.next();
            if (reader instanceof GIFImageReader) {
                type = "image/gif";
            } else if (reader instanceof JPEGImageReader) {
                type = "image/jpeg";
            } else if (reader instanceof PNGImageReader) {
                type = "image/png";
            } else if (reader instanceof BMPImageReader) {
                type = "application/x-bmp";
            }
        }
    } finally {
        if (bais != null) {
            try {
                bais.close();
            } catch (IOException ioe) {
            }
        }
        if (mcis != null) {
            try {
                mcis.close();
            } catch (IOException ioe) {
            }
        }
    }
    return type;
}
Also used : JPEGImageReader(com.sun.imageio.plugins.jpeg.JPEGImageReader) BMPImageReader(com.sun.imageio.plugins.bmp.BMPImageReader) ByteArrayInputStream(java.io.ByteArrayInputStream) PNGImageReader(com.sun.imageio.plugins.png.PNGImageReader) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) Iterator(java.util.Iterator) IOException(java.io.IOException) GIFImageReader(com.sun.imageio.plugins.gif.GIFImageReader) ImageReader(javax.imageio.ImageReader) JPEGImageReader(com.sun.imageio.plugins.jpeg.JPEGImageReader) BMPImageReader(com.sun.imageio.plugins.bmp.BMPImageReader) PNGImageReader(com.sun.imageio.plugins.png.PNGImageReader) GIFImageReader(com.sun.imageio.plugins.gif.GIFImageReader)

Example 5 with ImageReader

use of javax.imageio.ImageReader in project robolectric by robolectric.

the class ImageUtil method getImageSizeFromStream.

public static Point getImageSizeFromStream(InputStream is) {
    if (!initialized) {
        // Stops ImageIO from creating temp files when reading images
        // from input stream.
        ImageIO.setUseCache(false);
        initialized = true;
    }
    try {
        ImageInputStream imageStream = ImageIO.createImageInputStream(is);
        Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream);
        if (!readers.hasNext())
            return null;
        ImageReader reader = readers.next();
        try {
            reader.setInput(imageStream);
            return new Point(reader.getWidth(0), reader.getHeight(0));
        } finally {
            reader.dispose();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : ImageInputStream(javax.imageio.stream.ImageInputStream) Point(android.graphics.Point) IOException(java.io.IOException) ImageReader(javax.imageio.ImageReader)

Aggregations

ImageReader (javax.imageio.ImageReader)58 BufferedImage (java.awt.image.BufferedImage)32 ImageInputStream (javax.imageio.stream.ImageInputStream)32 IOException (java.io.IOException)22 ByteArrayInputStream (java.io.ByteArrayInputStream)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)14 ImageReadParam (javax.imageio.ImageReadParam)14 ImageWriter (javax.imageio.ImageWriter)13 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)11 MemoryCacheImageInputStream (javax.imageio.stream.MemoryCacheImageInputStream)11 Iterator (java.util.Iterator)10 InputStream (java.io.InputStream)9 IIOImage (javax.imageio.IIOImage)9 IIOMetadata (javax.imageio.metadata.IIOMetadata)9 ImageOutputStream (javax.imageio.stream.ImageOutputStream)7 File (java.io.File)5 ImageWriteParam (javax.imageio.ImageWriteParam)5 ImageReaderSpi (javax.imageio.spi.ImageReaderSpi)4 Graphics (java.awt.Graphics)3 Graphics2D (java.awt.Graphics2D)3