Search in sources :

Example 1 with DataBufferUShort

use of java.awt.image.DataBufferUShort in project processing by processing.

the class QuickTimeWriter method writeFrame.

/**
     * Encodes an image as a video frame and writes it into a video track.
     * <p>
     * Only the video encodings listed below are supported by this method.
     * For other encodings, you have to encode the image by yourself and then
     * call one of the {@code writeSample} methods.
     * <ul>
     * <li>RAW</li>
     * <li>JPG</li>
     * <li>PNG</li>
     * </ul>
     *
     * @param track The track index.
     * @param image The image of the video frame.
     * @param duration The duration of the video frame in media time scale units.
     *
     * @throws IndexOutofBoundsException if the track index is out of bounds.
     * @throws if the duration is less than 1, or if the dimension of the frame
     * does not match the dimension of the video.
     * @throws UnsupportedOperationException if the QuickTimeWriter does not have
     * a built-in encoder for this video format.
     * @throws IOException if writing the sample data failed.
     */
public void writeFrame(int track, BufferedImage image, long duration) throws IOException {
    if (duration <= 0) {
        throw new IllegalArgumentException("Duration must be greater 0.");
    }
    // throws index out of bounds exception if illegal track index
    VideoTrack t = (VideoTrack) tracks.get(track);
    if (t.mediaType != MediaType.VIDEO) {
        throw new IllegalArgumentException("Track " + track + " is not a video track");
    }
    if (t.videoEncoding == null) {
        throw new UnsupportedOperationException("Encoding not supported.");
    }
    ensureStarted();
    // The dimension of the image must match the dimension of the video track
    if (t.videoWidth != image.getWidth() || t.videoHeight != image.getHeight()) {
        throw new IllegalArgumentException("Dimensions of frame[" + tracks.get(track).getSampleCount() + "] (width=" + image.getWidth() + ", height=" + image.getHeight() + ") differs from video dimension (width=" + t.videoWidth + ", height=" + t.videoHeight + ") in track " + track + ".");
    }
    long offset = getRelativeStreamPosition();
    boolean isSync;
    switch(t.videoEncoding) {
        case RAW:
            {
                isSync = true;
                switch(t.videoDepth) {
                    case 8:
                        {
                            if (image.getType() != BufferedImage.TYPE_BYTE_INDEXED) {
                                throw new IllegalArgumentException("BufferedImage type " + image.getType() + " does not match track type " + BufferedImage.TYPE_BYTE_INDEXED + ".");
                            }
                            // Handle sub-image
                            WritableRaster raster = image.getRaster();
                            int sw = raster.getSampleModel().getWidth();
                            //                        int sh = raster.getSampleModel().getHeight();
                            Rectangle r = raster.getBounds();
                            r.x -= raster.getSampleModelTranslateX();
                            r.y -= raster.getSampleModelTranslateY();
                            DataBufferByte buf = (DataBufferByte) raster.getDataBuffer();
                            byte[] bytes = buf.getData();
                            // Write the samples
                            for (int xy = r.x + r.y * sw, ymax = r.x + (r.y + r.height) * sw; xy < ymax; xy += sw) {
                                mdatAtom.getOutputStream().write(bytes, xy, r.width);
                            }
                            break;
                        }
                    case 24:
                        {
                            WritableRaster raster = image.getRaster();
                            // holds a scanline of raw image data with 3 channels of 32 bit data
                            int[] rgb = new int[t.videoWidth * 3];
                            // holds a scanline of raw image data with 3 channels of 8 bit data
                            byte[] bytes = new byte[t.videoWidth * 3];
                            for (int y = 0; y < t.videoHeight; y++) {
                                // Note: Method getPixels is very slow as it does sample conversions for us
                                rgb = raster.getPixels(0, y, t.videoWidth, 1, rgb);
                                for (int k = 0, n = t.videoWidth * 3; k < n; k++) {
                                    bytes[k] = (byte) rgb[k];
                                }
                                mdatAtom.getOutputStream().write(bytes);
                            }
                            break;
                        }
                    default:
                        throw new UnsupportedOperationException("Encoding not supported.");
                }
                break;
            }
        case JPG:
            {
                isSync = true;
                ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/jpeg").next();
                ImageWriteParam iwParam = iw.getDefaultWriteParam();
                iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwParam.setCompressionQuality(t.videoQuality);
                MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(mdatAtom.getOutputStream());
                iw.setOutput(imgOut);
                IIOImage img = new IIOImage(image, null, null);
                iw.write(null, img, iwParam);
                iw.dispose();
                break;
            }
        case PNG:
            {
                isSync = true;
                ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
                ImageWriteParam iwParam = iw.getDefaultWriteParam();
                // FIXME - Detect number of bits per pixel, ensure that correct value is written into video media header atom.
                // FIXME - Maybe we should quietly enforce 24 bits per pixel
                MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(mdatAtom.getOutputStream());
                iw.setOutput(imgOut);
                IIOImage img = new IIOImage(image, null, null);
                iw.write(null, img, iwParam);
                iw.dispose();
                break;
            }
        case RLE:
            {
                isSync = t.previousData == null || t.syncInterval != 0 && t.sampleCount % t.syncInterval == 0;
                // Handle sub-image
                WritableRaster raster = image.getRaster();
                int sw = raster.getSampleModel().getWidth();
                //                int sh = raster.getSampleModel().getHeight();
                Rectangle r = raster.getBounds();
                r.x -= raster.getSampleModelTranslateX();
                r.y -= raster.getSampleModelTranslateY();
                if (t.encoder == null) {
                    t.encoder = new AppleRLEEncoder();
                }
                AppleRLEEncoder enc = t.encoder;
                switch(t.videoDepth) {
                    case 16:
                        {
                            DataBufferUShort buf = (DataBufferUShort) raster.getDataBuffer();
                            short[] data = buf.getData();
                            if (isSync) {
                                enc.writeKey16(mdatAtom.getOutputStream(), data, r.width, r.height, r.x + r.y * sw, sw);
                            } else {
                                // FIXME - We blindly assume that the sub-image of the previous image is the same as the current one
                                enc.writeDelta16(mdatAtom.getOutputStream(), data, (short[]) t.previousData, r.width, r.height, r.x + r.y * sw, sw);
                            }
                            if (t.previousData == null) {
                                t.previousData = new short[data.length];
                            }
                            System.arraycopy(data, 0, t.previousData, 0, data.length);
                            break;
                        }
                    case 24:
                        {
                            DataBufferInt buf = (DataBufferInt) raster.getDataBuffer();
                            int[] data = buf.getData();
                            if (isSync) {
                                enc.writeKey24(mdatAtom.getOutputStream(), data, r.width, r.height, r.x + r.y * sw, sw);
                            } else {
                                // FIXME - We blindly assume that the sub-image of the previous image is the same as the current one
                                enc.writeDelta24(mdatAtom.getOutputStream(), data, (int[]) t.previousData, r.width, r.height, r.x + r.y * sw, sw);
                            }
                            if (t.previousData == null) {
                                t.previousData = new int[data.length];
                            }
                            System.arraycopy(data, 0, t.previousData, 0, data.length);
                            break;
                        }
                    case 32:
                        {
                            DataBufferInt buf = (DataBufferInt) raster.getDataBuffer();
                            int[] data = buf.getData();
                            if (isSync) {
                                enc.writeKey32(mdatAtom.getOutputStream(), data, image.getWidth(), image.getHeight(), 0, image.getWidth());
                            } else {
                                // FIXME - We blindly assume that the sub-image of the previous image is the same as the current one
                                enc.writeDelta32(mdatAtom.getOutputStream(), data, (int[]) t.previousData, image.getWidth(), image.getHeight(), 0, image.getWidth());
                            }
                            if (t.previousData == null) {
                                t.previousData = new int[data.length];
                            }
                            System.arraycopy(data, 0, t.previousData, 0, data.length);
                            break;
                        }
                    default:
                        throw new UnsupportedOperationException("Encoding not supported.");
                }
                break;
            }
        default:
            {
                throw new UnsupportedOperationException("Encoding not supported.");
            }
    }
    long length = getRelativeStreamPosition() - offset;
    t.addSample(new Sample(duration, offset, length), 1, isSync);
}
Also used : Rectangle(java.awt.Rectangle) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) WritableRaster(java.awt.image.WritableRaster) DataBufferUShort(java.awt.image.DataBufferUShort)

Example 2 with DataBufferUShort

use of java.awt.image.DataBufferUShort in project jdk8u_jdk by JetBrains.

the class BMPImageWriter method write.

public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (stream == null) {
        throw new IllegalStateException(I18N.getString("BMPImageWriter7"));
    }
    if (image == null) {
        throw new IllegalArgumentException(I18N.getString("BMPImageWriter8"));
    }
    clearAbortRequest();
    processImageStarted(0);
    if (param == null)
        param = getDefaultWriteParam();
    BMPImageWriteParam bmpParam = (BMPImageWriteParam) param;
    // Default is using 24 bits per pixel.
    int bitsPerPixel = 24;
    boolean isPalette = false;
    int paletteEntries = 0;
    IndexColorModel icm = null;
    RenderedImage input = null;
    Raster inputRaster = null;
    boolean writeRaster = image.hasRaster();
    Rectangle sourceRegion = param.getSourceRegion();
    SampleModel sampleModel = null;
    ColorModel colorModel = null;
    compImageSize = 0;
    if (writeRaster) {
        inputRaster = image.getRaster();
        sampleModel = inputRaster.getSampleModel();
        colorModel = ImageUtil.createColorModel(null, sampleModel);
        if (sourceRegion == null)
            sourceRegion = inputRaster.getBounds();
        else
            sourceRegion = sourceRegion.intersection(inputRaster.getBounds());
    } else {
        input = image.getRenderedImage();
        sampleModel = input.getSampleModel();
        colorModel = input.getColorModel();
        Rectangle rect = new Rectangle(input.getMinX(), input.getMinY(), input.getWidth(), input.getHeight());
        if (sourceRegion == null)
            sourceRegion = rect;
        else
            sourceRegion = sourceRegion.intersection(rect);
    }
    IIOMetadata imageMetadata = image.getMetadata();
    BMPMetadata bmpImageMetadata = null;
    if (imageMetadata != null && imageMetadata instanceof BMPMetadata) {
        bmpImageMetadata = (BMPMetadata) imageMetadata;
    } else {
        ImageTypeSpecifier imageType = new ImageTypeSpecifier(colorModel, sampleModel);
        bmpImageMetadata = (BMPMetadata) getDefaultImageMetadata(imageType, param);
    }
    if (sourceRegion.isEmpty())
        throw new RuntimeException(I18N.getString("BMPImageWrite0"));
    int scaleX = param.getSourceXSubsampling();
    int scaleY = param.getSourceYSubsampling();
    int xOffset = param.getSubsamplingXOffset();
    int yOffset = param.getSubsamplingYOffset();
    // cache the data type;
    int dataType = sampleModel.getDataType();
    sourceRegion.translate(xOffset, yOffset);
    sourceRegion.width -= xOffset;
    sourceRegion.height -= yOffset;
    int minX = sourceRegion.x / scaleX;
    int minY = sourceRegion.y / scaleY;
    w = (sourceRegion.width + scaleX - 1) / scaleX;
    h = (sourceRegion.height + scaleY - 1) / scaleY;
    xOffset = sourceRegion.x % scaleX;
    yOffset = sourceRegion.y % scaleY;
    Rectangle destinationRegion = new Rectangle(minX, minY, w, h);
    boolean noTransform = destinationRegion.equals(sourceRegion);
    // Raw data can only handle bytes, everything greater must be ASCII.
    int[] sourceBands = param.getSourceBands();
    boolean noSubband = true;
    int numBands = sampleModel.getNumBands();
    if (sourceBands != null) {
        sampleModel = sampleModel.createSubsetSampleModel(sourceBands);
        colorModel = null;
        noSubband = false;
        numBands = sampleModel.getNumBands();
    } else {
        sourceBands = new int[numBands];
        for (int i = 0; i < numBands; i++) sourceBands[i] = i;
    }
    int[] bandOffsets = null;
    boolean bgrOrder = true;
    if (sampleModel instanceof ComponentSampleModel) {
        bandOffsets = ((ComponentSampleModel) sampleModel).getBandOffsets();
        if (sampleModel instanceof BandedSampleModel) {
            // for images with BandedSampleModel we can not work
            //  with raster directly and must use writePixels()
            bgrOrder = false;
        } else {
            // In any other case we must use writePixels()
            for (int i = 0; i < bandOffsets.length; i++) {
                bgrOrder &= (bandOffsets[i] == (bandOffsets.length - i - 1));
            }
        }
    } else {
        if (sampleModel instanceof SinglePixelPackedSampleModel) {
            // BugId 4892214: we can not work with raster directly
            // if image have different color order than RGB.
            // We should use writePixels() for such images.
            int[] bitOffsets = ((SinglePixelPackedSampleModel) sampleModel).getBitOffsets();
            for (int i = 0; i < bitOffsets.length - 1; i++) {
                bgrOrder &= bitOffsets[i] > bitOffsets[i + 1];
            }
        }
    }
    if (bandOffsets == null) {
        // we will use getPixels() to extract pixel data for writePixels()
        // Please note that getPixels() provides rgb bands order.
        bandOffsets = new int[numBands];
        for (int i = 0; i < numBands; i++) bandOffsets[i] = i;
    }
    noTransform &= bgrOrder;
    int[] sampleSize = sampleModel.getSampleSize();
    //XXX: check more
    // Number of bytes that a scanline for the image written out will have.
    int destScanlineBytes = w * numBands;
    switch(bmpParam.getCompressionMode()) {
        case ImageWriteParam.MODE_EXPLICIT:
            compressionType = BMPCompressionTypes.getType(bmpParam.getCompressionType());
            break;
        case ImageWriteParam.MODE_COPY_FROM_METADATA:
            compressionType = bmpImageMetadata.compression;
            break;
        case ImageWriteParam.MODE_DEFAULT:
            compressionType = getPreferredCompressionType(colorModel, sampleModel);
            break;
        default:
            // ImageWriteParam.MODE_DISABLED:
            compressionType = BI_RGB;
    }
    if (!canEncodeImage(compressionType, colorModel, sampleModel)) {
        throw new IOException("Image can not be encoded with compression type " + BMPCompressionTypes.getName(compressionType));
    }
    byte[] r = null, g = null, b = null, a = null;
    if (compressionType == BI_BITFIELDS) {
        bitsPerPixel = DataBuffer.getDataTypeSize(sampleModel.getDataType());
        if (bitsPerPixel != 16 && bitsPerPixel != 32) {
            // we should use 32bpp images in case of BI_BITFIELD
            // compression to avoid color conversion artefacts
            bitsPerPixel = 32;
            // Setting this flag to false ensures that generic
            // writePixels() will be used to store image data
            noTransform = false;
        }
        destScanlineBytes = w * bitsPerPixel + 7 >> 3;
        isPalette = true;
        paletteEntries = 3;
        r = new byte[paletteEntries];
        g = new byte[paletteEntries];
        b = new byte[paletteEntries];
        a = new byte[paletteEntries];
        int rmask = 0x00ff0000;
        int gmask = 0x0000ff00;
        int bmask = 0x000000ff;
        if (bitsPerPixel == 16) {
            /* NB: canEncodeImage() ensures we have image of
                 * either USHORT_565_RGB or USHORT_555_RGB type here.
                 * Technically, it should work for other direct color
                 * model types but it might be non compatible with win98
                 * and friends.
                 */
            if (colorModel instanceof DirectColorModel) {
                DirectColorModel dcm = (DirectColorModel) colorModel;
                rmask = dcm.getRedMask();
                gmask = dcm.getGreenMask();
                bmask = dcm.getBlueMask();
            } else {
                // an exception related to unsupported image format
                throw new IOException("Image can not be encoded with " + "compression type " + BMPCompressionTypes.getName(compressionType));
            }
        }
        writeMaskToPalette(rmask, 0, r, g, b, a);
        writeMaskToPalette(gmask, 1, r, g, b, a);
        writeMaskToPalette(bmask, 2, r, g, b, a);
        if (!noTransform) {
            // prepare info for writePixels procedure
            bitMasks = new int[3];
            bitMasks[0] = rmask;
            bitMasks[1] = gmask;
            bitMasks[2] = bmask;
            bitPos = new int[3];
            bitPos[0] = firstLowBit(rmask);
            bitPos[1] = firstLowBit(gmask);
            bitPos[2] = firstLowBit(bmask);
        }
        if (colorModel instanceof IndexColorModel) {
            icm = (IndexColorModel) colorModel;
        }
    } else {
        // handle BI_RGB compression
        if (colorModel instanceof IndexColorModel) {
            isPalette = true;
            icm = (IndexColorModel) colorModel;
            paletteEntries = icm.getMapSize();
            if (paletteEntries <= 2) {
                bitsPerPixel = 1;
                destScanlineBytes = w + 7 >> 3;
            } else if (paletteEntries <= 16) {
                bitsPerPixel = 4;
                destScanlineBytes = w + 1 >> 1;
            } else if (paletteEntries <= 256) {
                bitsPerPixel = 8;
            } else {
                // Cannot be written as a Palette image. So write out as
                // 24 bit image.
                bitsPerPixel = 24;
                isPalette = false;
                paletteEntries = 0;
                destScanlineBytes = w * 3;
            }
            if (isPalette == true) {
                r = new byte[paletteEntries];
                g = new byte[paletteEntries];
                b = new byte[paletteEntries];
                a = new byte[paletteEntries];
                icm.getAlphas(a);
                icm.getReds(r);
                icm.getGreens(g);
                icm.getBlues(b);
            }
        } else {
            // Grey scale images
            if (numBands == 1) {
                isPalette = true;
                paletteEntries = 256;
                bitsPerPixel = sampleSize[0];
                destScanlineBytes = (w * bitsPerPixel + 7 >> 3);
                r = new byte[256];
                g = new byte[256];
                b = new byte[256];
                a = new byte[256];
                for (int i = 0; i < 256; i++) {
                    r[i] = (byte) i;
                    g[i] = (byte) i;
                    b[i] = (byte) i;
                    a[i] = (byte) 255;
                }
            } else {
                if (sampleModel instanceof SinglePixelPackedSampleModel && noSubband) {
                    /* NB: the actual pixel size can be smaller than
                         * size of used DataBuffer element.
                         * For example: in case of TYPE_INT_RGB actual pixel
                         * size is 24 bits, but size of DataBuffere element
                         * is 32 bits
                         */
                    int[] sample_sizes = sampleModel.getSampleSize();
                    bitsPerPixel = 0;
                    for (int size : sample_sizes) {
                        bitsPerPixel += size;
                    }
                    bitsPerPixel = roundBpp(bitsPerPixel);
                    if (bitsPerPixel != DataBuffer.getDataTypeSize(sampleModel.getDataType())) {
                        noTransform = false;
                    }
                    destScanlineBytes = w * bitsPerPixel + 7 >> 3;
                }
            }
        }
    }
    // actual writing of image data
    int fileSize = 0;
    int offset = 0;
    int headerSize = 0;
    int imageSize = 0;
    int xPelsPerMeter = 0;
    int yPelsPerMeter = 0;
    int colorsUsed = 0;
    int colorsImportant = paletteEntries;
    // Calculate padding for each scanline
    int padding = destScanlineBytes % 4;
    if (padding != 0) {
        padding = 4 - padding;
    }
    // FileHeader is 14 bytes, BitmapHeader is 40 bytes,
    // add palette size and that is where the data will begin
    offset = 54 + paletteEntries * 4;
    imageSize = (destScanlineBytes + padding) * h;
    fileSize = imageSize + offset;
    headerSize = 40;
    long headPos = stream.getStreamPosition();
    writeFileHeader(fileSize, offset);
    /* According to MSDN description, the top-down image layout
         * is allowed only if compression type is BI_RGB or BI_BITFIELDS.
         * Images with any other compression type must be wrote in the
         * bottom-up layout.
         */
    if (compressionType == BI_RGB || compressionType == BI_BITFIELDS) {
        isTopDown = bmpParam.isTopDown();
    } else {
        isTopDown = false;
    }
    writeInfoHeader(headerSize, bitsPerPixel);
    // compression
    stream.writeInt(compressionType);
    // imageSize
    stream.writeInt(imageSize);
    // xPelsPerMeter
    stream.writeInt(xPelsPerMeter);
    // yPelsPerMeter
    stream.writeInt(yPelsPerMeter);
    // Colors Used
    stream.writeInt(colorsUsed);
    // Colors Important
    stream.writeInt(colorsImportant);
    // palette
    if (isPalette == true) {
        // write palette
        if (compressionType == BI_BITFIELDS) {
            // write masks for red, green and blue components.
            for (int i = 0; i < 3; i++) {
                int mask = (a[i] & 0xFF) + ((r[i] & 0xFF) * 0x100) + ((g[i] & 0xFF) * 0x10000) + ((b[i] & 0xFF) * 0x1000000);
                stream.writeInt(mask);
            }
        } else {
            for (int i = 0; i < paletteEntries; i++) {
                stream.writeByte(b[i]);
                stream.writeByte(g[i]);
                stream.writeByte(r[i]);
                stream.writeByte(a[i]);
            }
        }
    }
    // Writing of actual image data
    int scanlineBytes = w * numBands;
    // Buffer for up to 8 rows of pixels
    int[] pixels = new int[scanlineBytes * scaleX];
    // Also create a buffer to hold one line of the data
    // to be written to the file, so we can use array writes.
    bpixels = new byte[destScanlineBytes];
    int l;
    if (compressionType == BI_JPEG || compressionType == BI_PNG) {
        // prepare embedded buffer
        embedded_stream = new ByteArrayOutputStream();
        writeEmbedded(image, bmpParam);
        // update the file/image Size
        embedded_stream.flush();
        imageSize = embedded_stream.size();
        long endPos = stream.getStreamPosition();
        fileSize = (int) (offset + imageSize);
        stream.seek(headPos);
        writeSize(fileSize, 2);
        stream.seek(headPos);
        writeSize(imageSize, 34);
        stream.seek(endPos);
        stream.write(embedded_stream.toByteArray());
        embedded_stream = null;
        if (abortRequested()) {
            processWriteAborted();
        } else {
            processImageComplete();
            stream.flushBefore(stream.getStreamPosition());
        }
        return;
    }
    int maxBandOffset = bandOffsets[0];
    for (int i = 1; i < bandOffsets.length; i++) if (bandOffsets[i] > maxBandOffset)
        maxBandOffset = bandOffsets[i];
    int[] pixel = new int[maxBandOffset + 1];
    int destScanlineLength = destScanlineBytes;
    if (noTransform && noSubband) {
        destScanlineLength = destScanlineBytes / (DataBuffer.getDataTypeSize(dataType) >> 3);
    }
    for (int i = 0; i < h; i++) {
        if (abortRequested()) {
            break;
        }
        int row = minY + i;
        if (!isTopDown)
            row = minY + h - i - 1;
        // Get the pixels
        Raster src = inputRaster;
        Rectangle srcRect = new Rectangle(minX * scaleX + xOffset, row * scaleY + yOffset, (w - 1) * scaleX + 1, 1);
        if (!writeRaster)
            src = input.getData(srcRect);
        if (noTransform && noSubband) {
            SampleModel sm = src.getSampleModel();
            int pos = 0;
            int startX = srcRect.x - src.getSampleModelTranslateX();
            int startY = srcRect.y - src.getSampleModelTranslateY();
            if (sm instanceof ComponentSampleModel) {
                ComponentSampleModel csm = (ComponentSampleModel) sm;
                pos = csm.getOffset(startX, startY, 0);
                for (int nb = 1; nb < csm.getNumBands(); nb++) {
                    if (pos > csm.getOffset(startX, startY, nb)) {
                        pos = csm.getOffset(startX, startY, nb);
                    }
                }
            } else if (sm instanceof MultiPixelPackedSampleModel) {
                MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sm;
                pos = mppsm.getOffset(startX, startY);
            } else if (sm instanceof SinglePixelPackedSampleModel) {
                SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sm;
                pos = sppsm.getOffset(startX, startY);
            }
            if (compressionType == BI_RGB || compressionType == BI_BITFIELDS) {
                switch(dataType) {
                    case DataBuffer.TYPE_BYTE:
                        byte[] bdata = ((DataBufferByte) src.getDataBuffer()).getData();
                        stream.write(bdata, pos, destScanlineLength);
                        break;
                    case DataBuffer.TYPE_SHORT:
                        short[] sdata = ((DataBufferShort) src.getDataBuffer()).getData();
                        stream.writeShorts(sdata, pos, destScanlineLength);
                        break;
                    case DataBuffer.TYPE_USHORT:
                        short[] usdata = ((DataBufferUShort) src.getDataBuffer()).getData();
                        stream.writeShorts(usdata, pos, destScanlineLength);
                        break;
                    case DataBuffer.TYPE_INT:
                        int[] idata = ((DataBufferInt) src.getDataBuffer()).getData();
                        stream.writeInts(idata, pos, destScanlineLength);
                        break;
                }
                for (int k = 0; k < padding; k++) {
                    stream.writeByte(0);
                }
            } else if (compressionType == BI_RLE4) {
                if (bpixels == null || bpixels.length < scanlineBytes)
                    bpixels = new byte[scanlineBytes];
                src.getPixels(srcRect.x, srcRect.y, srcRect.width, srcRect.height, pixels);
                for (int h = 0; h < scanlineBytes; h++) {
                    bpixels[h] = (byte) pixels[h];
                }
                encodeRLE4(bpixels, scanlineBytes);
            } else if (compressionType == BI_RLE8) {
                //System.arraycopy(bdata, pos, bpixels, 0, scanlineBytes);
                if (bpixels == null || bpixels.length < scanlineBytes)
                    bpixels = new byte[scanlineBytes];
                src.getPixels(srcRect.x, srcRect.y, srcRect.width, srcRect.height, pixels);
                for (int h = 0; h < scanlineBytes; h++) {
                    bpixels[h] = (byte) pixels[h];
                }
                encodeRLE8(bpixels, scanlineBytes);
            }
        } else {
            src.getPixels(srcRect.x, srcRect.y, srcRect.width, srcRect.height, pixels);
            if (scaleX != 1 || maxBandOffset != numBands - 1) {
                for (int j = 0, k = 0, n = 0; j < w; j++, k += scaleX * numBands, n += numBands) {
                    System.arraycopy(pixels, k, pixel, 0, pixel.length);
                    for (int m = 0; m < numBands; m++) {
                        // pixel data is provided here in RGB order
                        pixels[n + m] = pixel[sourceBands[m]];
                    }
                }
            }
            writePixels(0, scanlineBytes, bitsPerPixel, pixels, padding, numBands, icm);
        }
        processImageProgress(100.0f * (((float) i) / ((float) h)));
    }
    if (compressionType == BI_RLE4 || compressionType == BI_RLE8) {
        // Write the RLE EOF marker and
        stream.writeByte(0);
        stream.writeByte(1);
        incCompImageSize(2);
        // update the file/image Size
        imageSize = compImageSize;
        fileSize = compImageSize + offset;
        long endPos = stream.getStreamPosition();
        stream.seek(headPos);
        writeSize(fileSize, 2);
        stream.seek(headPos);
        writeSize(imageSize, 34);
        stream.seek(endPos);
    }
    if (abortRequested()) {
        processWriteAborted();
    } else {
        processImageComplete();
        stream.flushBefore(stream.getStreamPosition());
    }
}
Also used : Rectangle(java.awt.Rectangle) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) ComponentSampleModel(java.awt.image.ComponentSampleModel) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) DataBufferShort(java.awt.image.DataBufferShort) IndexColorModel(java.awt.image.IndexColorModel) DirectColorModel(java.awt.image.DirectColorModel) ColorModel(java.awt.image.ColorModel) BandedSampleModel(java.awt.image.BandedSampleModel) DirectColorModel(java.awt.image.DirectColorModel) DataBufferUShort(java.awt.image.DataBufferUShort) IndexColorModel(java.awt.image.IndexColorModel) Raster(java.awt.image.Raster) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) BMPImageWriteParam(javax.imageio.plugins.bmp.BMPImageWriteParam) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IIOMetadata(javax.imageio.metadata.IIOMetadata) ComponentSampleModel(java.awt.image.ComponentSampleModel) SampleModel(java.awt.image.SampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) RenderedImage(java.awt.image.RenderedImage)

Example 3 with DataBufferUShort

use of java.awt.image.DataBufferUShort in project jdk8u_jdk by JetBrains.

the class ImageUtil method getUnpackedBinaryData.

/**
     * Returns the binary data unpacked into an array of bytes.
     * The line stride will be the width of the <code>Raster</code>.
     *
     * @throws IllegalArgumentException if <code>isBinary()</code> returns
     * <code>false</code> with the <code>SampleModel</code> of the
     * supplied <code>Raster</code> as argument.
     */
public static byte[] getUnpackedBinaryData(Raster raster, Rectangle rect) {
    SampleModel sm = raster.getSampleModel();
    if (!isBinary(sm)) {
        throw new IllegalArgumentException(I18N.getString("ImageUtil0"));
    }
    int rectX = rect.x;
    int rectY = rect.y;
    int rectWidth = rect.width;
    int rectHeight = rect.height;
    DataBuffer dataBuffer = raster.getDataBuffer();
    int dx = rectX - raster.getSampleModelTranslateX();
    int dy = rectY - raster.getSampleModelTranslateY();
    MultiPixelPackedSampleModel mpp = (MultiPixelPackedSampleModel) sm;
    int lineStride = mpp.getScanlineStride();
    int eltOffset = dataBuffer.getOffset() + mpp.getOffset(dx, dy);
    int bitOffset = mpp.getBitOffset(dx);
    byte[] bdata = new byte[rectWidth * rectHeight];
    int maxY = rectY + rectHeight;
    int maxX = rectX + rectWidth;
    int k = 0;
    if (dataBuffer instanceof DataBufferByte) {
        byte[] data = ((DataBufferByte) dataBuffer).getData();
        for (int y = rectY; y < maxY; y++) {
            int bOffset = eltOffset * 8 + bitOffset;
            for (int x = rectX; x < maxX; x++) {
                byte b = data[bOffset / 8];
                bdata[k++] = (byte) ((b >>> (7 - bOffset & 7)) & 0x0000001);
                bOffset++;
            }
            eltOffset += lineStride;
        }
    } else if (dataBuffer instanceof DataBufferShort || dataBuffer instanceof DataBufferUShort) {
        short[] data = dataBuffer instanceof DataBufferShort ? ((DataBufferShort) dataBuffer).getData() : ((DataBufferUShort) dataBuffer).getData();
        for (int y = rectY; y < maxY; y++) {
            int bOffset = eltOffset * 16 + bitOffset;
            for (int x = rectX; x < maxX; x++) {
                short s = data[bOffset / 16];
                bdata[k++] = (byte) ((s >>> (15 - bOffset % 16)) & 0x0000001);
                bOffset++;
            }
            eltOffset += lineStride;
        }
    } else if (dataBuffer instanceof DataBufferInt) {
        int[] data = ((DataBufferInt) dataBuffer).getData();
        for (int y = rectY; y < maxY; y++) {
            int bOffset = eltOffset * 32 + bitOffset;
            for (int x = rectX; x < maxX; x++) {
                int i = data[bOffset / 32];
                bdata[k++] = (byte) ((i >>> (31 - bOffset % 32)) & 0x0000001);
                bOffset++;
            }
            eltOffset += lineStride;
        }
    }
    return bdata;
}
Also used : DataBufferShort(java.awt.image.DataBufferShort) ComponentSampleModel(java.awt.image.ComponentSampleModel) SampleModel(java.awt.image.SampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) DataBufferUShort(java.awt.image.DataBufferUShort) Point(java.awt.Point) DataBuffer(java.awt.image.DataBuffer)

Example 4 with DataBufferUShort

use of java.awt.image.DataBufferUShort in project jdk8u_jdk by JetBrains.

the class BMPImageReader method read.

public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    if (iis == null) {
        throw new IllegalStateException(I18N.getString("BMPImageReader5"));
    }
    checkIndex(imageIndex);
    clearAbortRequest();
    processImageStarted(imageIndex);
    if (param == null)
        param = getDefaultReadParam();
    //read header
    try {
        readHeader();
    } catch (IllegalArgumentException e) {
        throw new IIOException(I18N.getString("BMPImageReader6"), e);
    }
    sourceRegion = new Rectangle(0, 0, 0, 0);
    destinationRegion = new Rectangle(0, 0, 0, 0);
    computeRegions(param, this.width, this.height, param.getDestination(), sourceRegion, destinationRegion);
    scaleX = param.getSourceXSubsampling();
    scaleY = param.getSourceYSubsampling();
    // If the destination band is set used it
    sourceBands = param.getSourceBands();
    destBands = param.getDestinationBands();
    seleBand = (sourceBands != null) && (destBands != null);
    noTransform = destinationRegion.equals(new Rectangle(0, 0, width, height)) || seleBand;
    if (!seleBand) {
        sourceBands = new int[numBands];
        destBands = new int[numBands];
        for (int i = 0; i < numBands; i++) destBands[i] = sourceBands[i] = i;
    }
    // If the destination is provided, then use it.  Otherwise, create new one
    bi = param.getDestination();
    // Get the image data.
    WritableRaster raster = null;
    if (bi == null) {
        if (sampleModel != null && colorModel != null) {
            sampleModel = sampleModel.createCompatibleSampleModel(destinationRegion.x + destinationRegion.width, destinationRegion.y + destinationRegion.height);
            if (seleBand)
                sampleModel = sampleModel.createSubsetSampleModel(sourceBands);
            raster = Raster.createWritableRaster(sampleModel, new Point());
            bi = new BufferedImage(colorModel, raster, false, null);
        }
    } else {
        raster = bi.getWritableTile(0, 0);
        sampleModel = bi.getSampleModel();
        colorModel = bi.getColorModel();
        noTransform &= destinationRegion.equals(raster.getBounds());
    }
    // buffer for byte data
    byte[] bdata = null;
    // buffer for short data
    short[] sdata = null;
    // buffer for int data
    int[] idata = null;
    // the sampleModel can be null in case of embedded image
    if (sampleModel != null) {
        if (sampleModel.getDataType() == DataBuffer.TYPE_BYTE)
            bdata = (byte[]) ((DataBufferByte) raster.getDataBuffer()).getData();
        else if (sampleModel.getDataType() == DataBuffer.TYPE_USHORT)
            sdata = (short[]) ((DataBufferUShort) raster.getDataBuffer()).getData();
        else if (sampleModel.getDataType() == DataBuffer.TYPE_INT)
            idata = (int[]) ((DataBufferInt) raster.getDataBuffer()).getData();
    }
    // There should only be one tile.
    switch(imageType) {
        case VERSION_2_1_BIT:
            // no compression
            read1Bit(bdata);
            break;
        case VERSION_2_4_BIT:
            // no compression
            read4Bit(bdata);
            break;
        case VERSION_2_8_BIT:
            // no compression
            read8Bit(bdata);
            break;
        case VERSION_2_24_BIT:
            // no compression
            read24Bit(bdata);
            break;
        case VERSION_3_1_BIT:
            // 1-bit images cannot be compressed.
            read1Bit(bdata);
            break;
        case VERSION_3_4_BIT:
            switch((int) compression) {
                case BI_RGB:
                    read4Bit(bdata);
                    break;
                case BI_RLE4:
                    readRLE4(bdata);
                    break;
                default:
                    throw new IIOException(I18N.getString("BMPImageReader1"));
            }
            break;
        case VERSION_3_8_BIT:
            switch((int) compression) {
                case BI_RGB:
                    read8Bit(bdata);
                    break;
                case BI_RLE8:
                    readRLE8(bdata);
                    break;
                default:
                    throw new IIOException(I18N.getString("BMPImageReader1"));
            }
            break;
        case VERSION_3_24_BIT:
            // 24-bit images are not compressed
            read24Bit(bdata);
            break;
        case VERSION_3_NT_16_BIT:
            read16Bit(sdata);
            break;
        case VERSION_3_NT_32_BIT:
            read32Bit(idata);
            break;
        case VERSION_3_XP_EMBEDDED:
        case VERSION_4_XP_EMBEDDED:
        case VERSION_5_XP_EMBEDDED:
            bi = readEmbedded((int) compression, bi, param);
            break;
        case VERSION_4_1_BIT:
            read1Bit(bdata);
            break;
        case VERSION_4_4_BIT:
            switch((int) compression) {
                case BI_RGB:
                    read4Bit(bdata);
                    break;
                case BI_RLE4:
                    readRLE4(bdata);
                    break;
                default:
                    throw new IIOException(I18N.getString("BMPImageReader1"));
            }
        case VERSION_4_8_BIT:
            switch((int) compression) {
                case BI_RGB:
                    read8Bit(bdata);
                    break;
                case BI_RLE8:
                    readRLE8(bdata);
                    break;
                default:
                    throw new IIOException(I18N.getString("BMPImageReader1"));
            }
            break;
        case VERSION_4_16_BIT:
            read16Bit(sdata);
            break;
        case VERSION_4_24_BIT:
            read24Bit(bdata);
            break;
        case VERSION_4_32_BIT:
            read32Bit(idata);
            break;
    }
    if (abortRequested())
        processReadAborted();
    else
        processImageComplete();
    return bi;
}
Also used : WritableRaster(java.awt.image.WritableRaster) Rectangle(java.awt.Rectangle) IIOException(javax.imageio.IIOException) Point(java.awt.Point) DataBufferUShort(java.awt.image.DataBufferUShort) Point(java.awt.Point) BufferedImage(java.awt.image.BufferedImage)

Example 5 with DataBufferUShort

use of java.awt.image.DataBufferUShort in project jdk8u_jdk by JetBrains.

the class PNGImageReader method createRaster.

private WritableRaster createRaster(int width, int height, int bands, int scanlineStride, int bitDepth) {
    DataBuffer dataBuffer;
    WritableRaster ras = null;
    Point origin = new Point(0, 0);
    if ((bitDepth < 8) && (bands == 1)) {
        dataBuffer = new DataBufferByte(height * scanlineStride);
        ras = Raster.createPackedRaster(dataBuffer, width, height, bitDepth, origin);
    } else if (bitDepth <= 8) {
        dataBuffer = new DataBufferByte(height * scanlineStride);
        ras = Raster.createInterleavedRaster(dataBuffer, width, height, scanlineStride, bands, bandOffsets[bands], origin);
    } else {
        dataBuffer = new DataBufferUShort(height * scanlineStride);
        ras = Raster.createInterleavedRaster(dataBuffer, width, height, scanlineStride, bands, bandOffsets[bands], origin);
    }
    return ras;
}
Also used : WritableRaster(java.awt.image.WritableRaster) Point(java.awt.Point) DataBufferByte(java.awt.image.DataBufferByte) DataBufferUShort(java.awt.image.DataBufferUShort) DataBuffer(java.awt.image.DataBuffer)

Aggregations

DataBufferUShort (java.awt.image.DataBufferUShort)8 DataBufferByte (java.awt.image.DataBufferByte)7 Point (java.awt.Point)6 DataBufferInt (java.awt.image.DataBufferInt)6 ComponentSampleModel (java.awt.image.ComponentSampleModel)5 DataBuffer (java.awt.image.DataBuffer)5 DataBufferShort (java.awt.image.DataBufferShort)5 MultiPixelPackedSampleModel (java.awt.image.MultiPixelPackedSampleModel)5 SampleModel (java.awt.image.SampleModel)5 SinglePixelPackedSampleModel (java.awt.image.SinglePixelPackedSampleModel)5 Rectangle (java.awt.Rectangle)3 WritableRaster (java.awt.image.WritableRaster)3 BandedSampleModel (java.awt.image.BandedSampleModel)1 BufferedImage (java.awt.image.BufferedImage)1 ColorModel (java.awt.image.ColorModel)1 DirectColorModel (java.awt.image.DirectColorModel)1 IndexColorModel (java.awt.image.IndexColorModel)1 Raster (java.awt.image.Raster)1 RenderedImage (java.awt.image.RenderedImage)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1