Example usage for javax.imageio.stream MemoryCacheImageInputStream MemoryCacheImageInputStream

List of usage examples for javax.imageio.stream MemoryCacheImageInputStream MemoryCacheImageInputStream

Introduction

In this page you can find the example usage for javax.imageio.stream MemoryCacheImageInputStream MemoryCacheImageInputStream.

Prototype

public MemoryCacheImageInputStream(InputStream stream) 

Source Link

Document

Constructs a MemoryCacheImageInputStream that will read from a given InputStream .

Usage

From source file:jails.http.converter.BufferedImageHttpMessageConverter.java

private ImageInputStream createImageInputStream(InputStream is) throws IOException {
    if (this.cacheDir != null) {
        return new FileCacheImageInputStream(is, cacheDir);
    } else {//from   w w w .  ja  v  a2 s  .  c o m
        return new MemoryCacheImageInputStream(is);
    }
}

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

public IIOMetadata getMetaData(Struct parent) {
    InputStream is = null;/*from ww  w  .ja v a2  s  .  c  o  m*/
    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;
}

From source file:org.apache.pdfbox.filter.LZWFilter.java

private void doLZWDecode(InputStream encoded, OutputStream decoded, int earlyChange) throws IOException {
    List<byte[]> codeTable = new ArrayList<byte[]>();
    int chunk = 9;
    final MemoryCacheImageInputStream in = new MemoryCacheImageInputStream(encoded);
    long nextCommand;
    long prevCommand = -1;

    try {/*  w ww.  j  a  v a 2  s.  com*/
        while ((nextCommand = in.readBits(chunk)) != EOD) {
            if (nextCommand == CLEAR_TABLE) {
                chunk = 9;
                codeTable = createCodeTable();
                prevCommand = -1;
            } else {
                if (nextCommand < codeTable.size()) {
                    byte[] data = codeTable.get((int) nextCommand);
                    byte firstByte = data[0];
                    decoded.write(data);
                    if (prevCommand != -1) {
                        checkIndexBounds(codeTable, prevCommand, in);
                        data = codeTable.get((int) prevCommand);
                        byte[] newData = Arrays.copyOf(data, data.length + 1);
                        newData[data.length] = firstByte;
                        codeTable.add(newData);
                    }
                } else {
                    checkIndexBounds(codeTable, prevCommand, in);
                    byte[] data = codeTable.get((int) prevCommand);
                    byte[] newData = Arrays.copyOf(data, data.length + 1);
                    newData[data.length] = data[0];
                    decoded.write(newData);
                    codeTable.add(newData);
                }

                chunk = calculateChunk(codeTable.size(), earlyChange);
                prevCommand = nextCommand;
            }
        }
    } catch (EOFException ex) {
        LOG.warn("Premature EOF in LZW stream, EOD code missing");
    }
    decoded.flush();
}

From source file:org.apache.pdfbox.pdmodel.graphics.image.SampledImageReader.java

private static BufferedImage fromAny(PDImage pdImage, WritableRaster raster, COSArray colorKey)
        throws IOException {
    final PDColorSpace colorSpace = pdImage.getColorSpace();
    final int numComponents = colorSpace.getNumberOfComponents();
    final int width = pdImage.getWidth();
    final int height = pdImage.getHeight();
    final int bitsPerComponent = pdImage.getBitsPerComponent();
    final float[] decode = getDecodeArray(pdImage);

    // read bit stream
    ImageInputStream iis = null;//from w  w  w .j  a  v  a 2  s.c  o  m
    try {
        // create stream
        iis = new MemoryCacheImageInputStream(pdImage.createInputStream());
        final float sampleMax = (float) Math.pow(2, bitsPerComponent) - 1f;
        final boolean isIndexed = colorSpace instanceof PDIndexed;

        // init color key mask
        float[] colorKeyRanges = null;
        BufferedImage colorKeyMask = null;
        if (colorKey != null) {
            colorKeyRanges = colorKey.toFloatArray();
            colorKeyMask = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        }

        // calculate row padding
        int padding = 0;
        if (width * numComponents * bitsPerComponent % 8 > 0) {
            padding = 8 - (width * numComponents * bitsPerComponent % 8);
        }

        // read stream
        byte[] srcColorValues = new byte[numComponents];
        byte[] alpha = new byte[1];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                boolean isMasked = true;
                for (int c = 0; c < numComponents; c++) {
                    int value = (int) iis.readBits(bitsPerComponent);

                    // color key mask requires values before they are decoded
                    if (colorKeyRanges != null) {
                        isMasked &= value >= colorKeyRanges[c * 2] && value <= colorKeyRanges[c * 2 + 1];
                    }

                    // decode array
                    final float dMin = decode[c * 2];
                    final float dMax = decode[(c * 2) + 1];

                    // interpolate to domain
                    float output = dMin + (value * ((dMax - dMin) / sampleMax));

                    if (isIndexed) {
                        // indexed color spaces get the raw value, because the TYPE_BYTE
                        // below cannot be reversed by the color space without it having
                        // knowledge of the number of bits per component
                        srcColorValues[c] = (byte) Math.round(output);
                    } else {
                        // interpolate to TYPE_BYTE
                        int outputByte = Math
                                .round(((output - Math.min(dMin, dMax)) / Math.abs(dMax - dMin)) * 255f);

                        srcColorValues[c] = (byte) outputByte;
                    }
                }
                raster.setDataElements(x, y, srcColorValues);

                // set alpha channel in color key mask, if any
                if (colorKeyMask != null) {
                    alpha[0] = (byte) (isMasked ? 255 : 0);
                    colorKeyMask.getRaster().setDataElements(x, y, alpha);
                }
            }

            // rows are padded to the nearest byte
            iis.readBits(padding);
        }

        // use the color space to convert the image to RGB
        BufferedImage rgbImage = colorSpace.toRGBImage(raster);

        // apply color mask, if any
        if (colorKeyMask != null) {
            return applyColorKeyMask(rgbImage, colorKeyMask);
        } else {
            return rgbImage;
        }
    } finally {
        if (iis != null) {
            iis.close();
        }
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.PatchMeshesShadingContext.java

/**
 * Create a patch list from a data stream, the returned list contains all the patches contained
 * in the data stream./*from  w ww  .  j a va 2  s. c om*/
 *
 * @param shadingType the shading type
 * @param xform transformation for user to device space
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @param controlPoints number of control points, 12 for type 6 shading and 16 for type 7 shading
 * @return the obtained patch list
 * @throws IOException when something went wrong
 */
final List<Patch> collectPatches(PDShadingType6 shadingType, AffineTransform xform, Matrix matrix,
        int controlPoints) throws IOException {
    COSDictionary dict = shadingType.getCOSObject();
    int bitsPerFlag = shadingType.getBitsPerFlag();
    PDRange rangeX = shadingType.getDecodeForParameter(0);
    PDRange rangeY = shadingType.getDecodeForParameter(1);
    PDRange[] colRange = new PDRange[numberOfColorComponents];
    for (int i = 0; i < numberOfColorComponents; ++i) {
        colRange[i] = shadingType.getDecodeForParameter(2 + i);
    }
    List<Patch> list = new ArrayList<Patch>();
    long maxSrcCoord = (long) Math.pow(2, bitsPerCoordinate) - 1;
    long maxSrcColor = (long) Math.pow(2, bitsPerColorComponent) - 1;
    COSStream cosStream = (COSStream) dict;

    ImageInputStream mciis = new MemoryCacheImageInputStream(cosStream.createInputStream());
    try {
        Point2D[] implicitEdge = new Point2D[4];
        float[][] implicitCornerColor = new float[2][numberOfColorComponents];
        byte flag = 0;

        try {
            flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
        } catch (EOFException ex) {
            LOG.error(ex);
        }

        while (true) {
            try {
                boolean isFree = (flag == 0);
                Patch current = readPatch(mciis, isFree, implicitEdge, implicitCornerColor, maxSrcCoord,
                        maxSrcColor, rangeX, rangeY, colRange, matrix, xform, controlPoints);
                if (current == null) {
                    break;
                }
                list.add(current);
                flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
                switch (flag) {
                case 0:
                    break;
                case 1:
                    implicitEdge = current.getFlag1Edge();
                    implicitCornerColor = current.getFlag1Color();
                    break;
                case 2:
                    implicitEdge = current.getFlag2Edge();
                    implicitCornerColor = current.getFlag2Color();
                    break;
                case 3:
                    implicitEdge = current.getFlag3Edge();
                    implicitCornerColor = current.getFlag3Color();
                    break;
                default:
                    LOG.warn("bad flag: " + flag);
                    break;
                }
            } catch (EOFException ex) {
                break;
            }
        }
    } finally {
        mciis.close();
    }
    return list;
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.Type4ShadingContext.java

private List<ShadedTriangle> collectTriangles(PDShadingType4 freeTriangleShadingType, AffineTransform xform,
        Matrix matrix) throws IOException {
    COSDictionary dict = freeTriangleShadingType.getCOSObject();
    PDRange rangeX = freeTriangleShadingType.getDecodeForParameter(0);
    PDRange rangeY = freeTriangleShadingType.getDecodeForParameter(1);
    PDRange[] colRange = new PDRange[numberOfColorComponents];
    for (int i = 0; i < numberOfColorComponents; ++i) {
        colRange[i] = freeTriangleShadingType.getDecodeForParameter(2 + i);
    }//  ww w . j  a  v  a  2  s. c om
    List<ShadedTriangle> list = new ArrayList<ShadedTriangle>();
    long maxSrcCoord = (long) Math.pow(2, bitsPerCoordinate) - 1;
    long maxSrcColor = (long) Math.pow(2, bitsPerColorComponent) - 1;
    COSStream stream = (COSStream) dict;

    ImageInputStream mciis = new MemoryCacheImageInputStream(stream.createInputStream());
    try {
        byte flag = (byte) 0;
        try {
            flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
        } catch (EOFException ex) {
            LOG.error(ex);
        }

        while (true) {
            Vertex p0, p1, p2;
            Point2D[] ps;
            float[][] cs;
            int lastIndex;
            try {
                switch (flag) {
                case 0:
                    p0 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform);
                    flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
                    if (flag != 0) {
                        LOG.error("bad triangle: " + flag);
                    }
                    p1 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform);
                    mciis.readBits(bitsPerFlag);
                    if (flag != 0) {
                        LOG.error("bad triangle: " + flag);
                    }
                    p2 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform);
                    ps = new Point2D[] { p0.point, p1.point, p2.point };
                    cs = new float[][] { p0.color, p1.color, p2.color };
                    list.add(new ShadedTriangle(ps, cs));
                    flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
                    break;
                case 1:
                case 2:
                    lastIndex = list.size() - 1;
                    if (lastIndex < 0) {
                        LOG.error("broken data stream: " + list.size());
                    } else {
                        ShadedTriangle preTri = list.get(lastIndex);
                        p2 = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix,
                                xform);
                        ps = new Point2D[] { flag == 1 ? preTri.corner[1] : preTri.corner[0], preTri.corner[2],
                                p2.point };
                        cs = new float[][] { flag == 1 ? preTri.color[1] : preTri.color[0], preTri.color[2],
                                p2.color };
                        list.add(new ShadedTriangle(ps, cs));
                        flag = (byte) (mciis.readBits(bitsPerFlag) & 3);
                    }
                    break;
                default:
                    LOG.warn("bad flag: " + flag);
                    break;
                }
            } catch (EOFException ex) {
                break;
            }
        }
    } finally {
        mciis.close();
    }
    return list;
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.Type5ShadingContext.java

private List<ShadedTriangle> collectTriangles(PDShadingType5 latticeTriangleShadingType, AffineTransform xform,
        Matrix matrix) throws IOException {
    COSDictionary cosDictionary = latticeTriangleShadingType.getCOSObject();
    PDRange rangeX = latticeTriangleShadingType.getDecodeForParameter(0);
    PDRange rangeY = latticeTriangleShadingType.getDecodeForParameter(1);
    int numPerRow = latticeTriangleShadingType.getVerticesPerRow();
    PDRange[] colRange = new PDRange[numberOfColorComponents];
    for (int i = 0; i < numberOfColorComponents; ++i) {
        colRange[i] = latticeTriangleShadingType.getDecodeForParameter(2 + i);
    }//from w  w  w .ja v  a2  s .c o m
    List<Vertex> vlist = new ArrayList<Vertex>();
    long maxSrcCoord = (long) Math.pow(2, bitsPerCoordinate) - 1;
    long maxSrcColor = (long) Math.pow(2, bitsPerColorComponent) - 1;
    COSStream cosStream = (COSStream) cosDictionary;

    ImageInputStream mciis = new MemoryCacheImageInputStream(cosStream.createInputStream());
    try {
        while (true) {
            Vertex p;
            try {
                p = readVertex(mciis, maxSrcCoord, maxSrcColor, rangeX, rangeY, colRange, matrix, xform);
                vlist.add(p);
            } catch (EOFException ex) {
                break;
            }
        }
    } finally {
        mciis.close();
    }
    int sz = vlist.size(), rowNum = sz / numPerRow;
    Vertex[][] latticeArray = new Vertex[rowNum][numPerRow];
    List<ShadedTriangle> list = new ArrayList<ShadedTriangle>();
    if (rowNum < 2) {
        // must have at least two rows; if not, return empty list
        return list;
    }
    for (int i = 0; i < rowNum; i++) {
        for (int j = 0; j < numPerRow; j++) {
            latticeArray[i][j] = vlist.get(i * numPerRow + j);
        }
    }

    for (int i = 0; i < rowNum - 1; i++) {
        for (int j = 0; j < numPerRow - 1; j++) {
            Point2D[] ps = new Point2D[] { latticeArray[i][j].point, latticeArray[i][j + 1].point,
                    latticeArray[i + 1][j].point };

            float[][] cs = new float[][] { latticeArray[i][j].color, latticeArray[i][j + 1].color,
                    latticeArray[i + 1][j].color };

            list.add(new ShadedTriangle(ps, cs));

            ps = new Point2D[] { latticeArray[i][j + 1].point, latticeArray[i + 1][j].point,
                    latticeArray[i + 1][j + 1].point };

            cs = new float[][] { latticeArray[i][j + 1].color, latticeArray[i + 1][j].color,
                    latticeArray[i + 1][j + 1].color };

            list.add(new ShadedTriangle(ps, cs));
        }
    }
    return list;
}

From source file:org.codice.imaging.nitf.core.AbstractWriterTest.java

protected void roundTripFile(String sourceFileName)
        throws URISyntaxException, NitfFormatException, IOException {
    String outputFile = FilenameUtils.getName(sourceFileName);
    NitfReader reader = new NitfInputStreamReader(new BufferedInputStream(getInputStream(sourceFileName)));
    SlottedParseStrategy parseStrategy = new SlottedParseStrategy(SlottedParseStrategy.ALL_SEGMENT_DATA);
    HeapStrategyConfiguration heapStrategyConfiguration = new HeapStrategyConfiguration(
            length -> length > ABOUT_100K);
    HeapStrategy<ImageInputStream> imageDataStrategy = new ConfigurableHeapStrategy<>(heapStrategyConfiguration,
            file -> new FileImageInputStream(file), is -> new MemoryCacheImageInputStream(is));
    parseStrategy.setImageHeapStrategy(imageDataStrategy);

    NitfParser.parse(reader, parseStrategy);
    NitfWriter writer = new NitfFileWriter(parseStrategy.getDataSource(), outputFile);
    writer.write();/*  w  w w. j a va2s  . c om*/
    assertTrue(FileUtils.contentEquals(new File(getClass().getResource(sourceFileName).toURI()),
            new File(outputFile)));
    assertTrue(new File(outputFile).delete());

    // Do the same again, but with stream writing
    try (OutputStream outputStream = new FileOutputStream(outputFile)) {
        writer = new NitfOutputStreamWriter(parseStrategy.getDataSource(), outputStream);
        writer.write();
        assertTrue(FileUtils.contentEquals(new File(getClass().getResource(sourceFileName).toURI()),
                new File(outputFile)));
    }
    assertTrue(new File(outputFile).delete());
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ScaleImageOperation.java

/**
 * Creates a scaled version of an image. The given scaling parameters define a bounding box with a certain width and
 * height. Images that do not fit in this box (i.e. are too large) are always scaled down such that they do fit. If
 * the aspect ratio of the original image differs from that of the bounding box, either the width or the height of
 * scaled image will be less than that of the box.</p> <p> Smaller images are scaled up in the same way as large
 * images are scaled down, but only if upscaling is true. When upscaling is false and the image is smaller than the
 * bounding box, the scaled image will be equal to the original.</p> <p> If the width or height of the scaling
 * parameters is 0 or less, that side of the bounding box does not exist (i.e. is unbounded). If both sides of the
 * bounding box are unbounded, the scaled image will be equal to the original.</p>
 *
 * @param data   the original image data
 * @param reader reader for the image data
 * @param writer writer for the image data
 *//* www  .  j  a v  a 2 s  . co m*/
public void execute(InputStream data, ImageReader reader, ImageWriter writer) throws IOException {
    // save the image data in a temporary file so we can reuse the original data as-is if needed without
    // putting all the data into memory
    final File tmpFile = writeToTmpFile(data);
    boolean deleteTmpFile = true;
    log.debug("Stored uploaded image in temporary file {}", tmpFile);

    InputStream dataInputStream = null;
    ImageInputStream imageInputStream = null;

    try {
        dataInputStream = new FileInputStream(tmpFile);
        imageInputStream = new MemoryCacheImageInputStream(dataInputStream);
        reader.setInput(imageInputStream);

        final int originalWidth = reader.getWidth(0);
        final int originalHeight = reader.getHeight(0);

        if (isOriginalVariant()) {
            scaledWidth = originalWidth;
            scaledHeight = originalHeight;
            scaledData = new AutoDeletingTmpFileInputStream(tmpFile);
            deleteTmpFile = false;
        } else {
            BufferedImage scaledImage = getScaledImage(reader, originalWidth, originalHeight);
            ByteArrayOutputStream scaledOutputStream = ImageUtils.writeImage(writer, scaledImage,
                    compressionQuality);

            scaledWidth = scaledImage.getWidth();
            scaledHeight = scaledImage.getHeight();
            scaledData = new ByteArrayInputStream(scaledOutputStream.toByteArray());
        }
    } finally {
        if (imageInputStream != null) {
            imageInputStream.close();
        }
        IOUtils.closeQuietly(dataInputStream);
        if (deleteTmpFile) {
            log.debug("Deleting temporary file {}", tmpFile);
            tmpFile.delete();
        }
    }
}

From source file:org.olat.core.commons.services.image.spi.AbstractImageHelper.java

private Size getImageSize(VFSLeaf media, String suffix) {
    Size result = null;//  w w w  .  j  a  v a 2s  . com
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageInputStream stream = null;
        InputStream mediaStream = null;
        ImageReader reader = iter.next();
        try {
            mediaStream = media.getInputStream();
            if (mediaStream != null) {
                stream = new MemoryCacheImageInputStream(mediaStream);
                reader.setInput(stream);
                int readerMinIndex = reader.getMinIndex();
                int width = reader.getWidth(readerMinIndex);
                int height = reader.getHeight(readerMinIndex);
                result = new Size(width, height, 0, 0, false);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            IOUtils.closeQuietly(stream);
            IOUtils.closeQuietly(mediaStream);
            reader.dispose();
        }
    } else {
        log.error("No reader found for given format: " + suffix);
    }
    return result;
}