Example usage for java.awt.image Raster createWritableRaster

List of usage examples for java.awt.image Raster createWritableRaster

Introduction

In this page you can find the example usage for java.awt.image Raster createWritableRaster.

Prototype

public static WritableRaster createWritableRaster(SampleModel sm, DataBuffer db, Point location) 

Source Link

Document

Creates a WritableRaster with the specified SampleModel and DataBuffer.

Usage

From source file:de.codesourcery.jasm16.emulator.devices.impl.RawImage.java

public RawImage(int width, int height) {
    data = new int[width * height];

    final DataBufferInt dataBuffer = new DataBufferInt(data, width * height);

    final ColorModel cm = new DirectColorModel(24, 0xff0000, 0xff00, 0xff);
    final SampleModel sm = cm.createCompatibleSampleModel(width, height);
    final WritableRaster wr = Raster.createWritableRaster(sm, dataBuffer, null);

    image = new BufferedImage(cm, wr, false, null);
}

From source file:GrabandFadewithRasters.java

public void init() {
    URL url;/*from ww  w  . j  a v  a  2s.c  o m*/
    try {
        url = new URL(imageURLString);
        originalImage = getImage(url);
    } catch (MalformedURLException me) {
        showStatus("Malformed URL: " + me.getMessage());
    }

    try {
        PixelGrabber grabber = new PixelGrabber(originalImage, 0, 0, -1, -1, true);
        if (grabber.grabPixels()) {
            width = grabber.getWidth();
            height = grabber.getHeight();
            originalPixelArray = (int[]) grabber.getPixels();

            mis = new MemoryImageSource(width, height, originalPixelArray, 0, width);
            mis.setAnimated(true);
            newImage = createImage(mis);
        } else {
            System.err.println("Grabbing Failed");
        }
    } catch (InterruptedException ie) {
        System.err.println("Pixel Grabbing Interrupted");
    }

    DataBufferInt dbi = new DataBufferInt(originalPixelArray, width * height);

    int bandmasks[] = { 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff };
    SampleModel sm;
    sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, width, height, bandmasks);

    raster = Raster.createWritableRaster(sm, dbi, null);
}

From source file:GraphicsUtil.java

/**
 * Coerces <tt>ras</tt> to be writable.  The returned Raster continues to
 * reference the DataBuffer from ras, so modifications to the returned
 * WritableRaster will be seen in ras.<p>
 *
 * You can specify a new location for the returned WritableRaster, this
 * is especially useful for constructing BufferedImages which require
 * the Raster to be at (0,0).// w  ww. ja v  a2  s .  c o m
 *
 * This method should only be used if you need a WritableRaster due to
 * an interface (such as to construct a BufferedImage), but have no
 * intention of modifying the contents of the returned Raster.  If
 * you have any doubt about other users of the data in <tt>ras</tt>,
 * use copyRaster (above).
 *
 * @param ras The raster to make writable.
 *
 * @param minX The x location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @param minY The y location for the upper left corner of the
 *             returned WritableRaster.
 *
 * @return A Writable version of <tT>ras</tt> with it's upper left
 *         hand coordinate set to minX, minY (shares it's DataBuffer
 *         with <tt>ras</tt>).
 */
public static WritableRaster makeRasterWritable(Raster ras, int minX, int minY) {
    WritableRaster ret = Raster.createWritableRaster(ras.getSampleModel(), ras.getDataBuffer(),
            new Point(0, 0));
    ret = ret.createWritableChild(ras.getMinX() - ras.getSampleModelTranslateX(),
            ras.getMinY() - ras.getSampleModelTranslateY(), ras.getWidth(), ras.getHeight(), minX, minY, null);
    return ret;
}

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

private BufferedImage jpgImage(BufferedImage src) {
    int w = src.getWidth();
    int h = src.getHeight();
    SampleModel srcSM = src.getSampleModel();
    WritableRaster srcWR = src.getRaster();
    java.awt.image.DataBuffer srcDB = srcWR.getDataBuffer();

    ColorModel rgb = new DirectColorModel(32, 0xff0000, 65280, 255);
    int[] bitMasks = new int[] { 0xff0000, 65280, 255 };

    SampleModel csm = new SinglePixelPackedSampleModel(3, w, h, bitMasks);
    int data[] = new int[w * h];
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            int pix[] = null;
            int sample[] = srcSM.getPixel(j, i, pix, srcDB);
            if (sample[3] == 0 && sample[2] == 0 && sample[1] == 0 && sample[0] == 0)
                data[i * w + j] = 0xffffff;
            else//from  w  w w .  j  a v  a 2  s  .c  o  m
                data[i * w + j] = sample[0] << 16 | sample[1] << 8 | sample[2];
        }

    }

    java.awt.image.DataBuffer db = new DataBufferInt(data, w * h * 3);
    WritableRaster wr = Raster.createWritableRaster(csm, db, new Point(0, 0));
    return new BufferedImage(rgb, wr, false, null);
}

From source file:org.geoserver.jai.ConcurrentTileFactory.java

/**
 * Builds a new tile, eventually recycling the data array backing it
 *///  w  ww  .j ava  2  s .  c o m
public WritableRaster createTile(SampleModel sampleModel, Point location) {
    // sanity checks
    if (sampleModel == null) {
        throw new NullPointerException("sampleModel cannot be null");
    }
    if (location == null) {
        location = new Point(0, 0);
    }

    DataBuffer db = null;

    // get the three elements making the key into the recycled array map
    int type = sampleModel.getTransferType();
    long numBanks = 0;
    long size = 0;
    if (sampleModel instanceof ComponentSampleModel) {
        ComponentSampleModel csm = (ComponentSampleModel) sampleModel;
        numBanks = getNumBanksCSM(csm);
        size = getBufferSizeCSM(csm);
    } else if (sampleModel instanceof MultiPixelPackedSampleModel) {
        MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sampleModel;
        numBanks = 1;
        int dataTypeSize = DataBuffer.getDataTypeSize(type);
        size = mppsm.getScanlineStride() * mppsm.getHeight()
                + (mppsm.getDataBitOffset() + dataTypeSize - 1) / dataTypeSize;
    } else if (sampleModel instanceof SinglePixelPackedSampleModel) {
        SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sampleModel;
        numBanks = 1;
        size = sppsm.getScanlineStride() * (sppsm.getHeight() - 1) + sppsm.getWidth();
    }

    if (size > 0) {
        // try to build a new data buffer starting from 
        Object array = recycledArrays.getRecycledArray(type, numBanks, size);
        if (array != null) {
            switch (type) {
            case DataBuffer.TYPE_BYTE: {
                byte[][] bankData = (byte[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (byte) 0);
                }
                db = new DataBufferByte(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_USHORT: {
                short[][] bankData = (short[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (short) 0);
                }
                db = new DataBufferUShort(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_SHORT: {
                short[][] bankData = (short[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (short) 0);
                }
                db = new DataBufferShort(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_INT: {
                int[][] bankData = (int[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0);
                }
                db = new DataBufferInt(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_FLOAT: {
                float[][] bankData = (float[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0.0F);
                }
                db = DataBufferUtils.createDataBufferFloat(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_DOUBLE: {
                double[][] bankData = (double[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0.0);
                }
                db = DataBufferUtils.createDataBufferDouble(bankData, (int) size);
            }
                break;
            default:
                throw new IllegalArgumentException("Unknown array type");
            }
        }
    }

    if (db == null) {
        db = sampleModel.createDataBuffer();
    }

    return Raster.createWritableRaster(sampleModel, db, location);
}

From source file:org.photovault.dcraw.RawImage.java

/**
 * Load the raw image using dcraw. No processing is yet done for the image,
 * however, the histogram & white point is calculated.
 *///from  w  w w .  j a  v  a2  s.  c o  m
private void loadRawImage() {
    long startTime = System.currentTimeMillis();
    log.debug("begin:loadRawImage");
    if (lrd == null) {
        openRaw();
        log.debug("openRaw() " + (System.currentTimeMillis() - startTime));
        if (lrd == null) {
            throw new IllegalStateException("Called loadRawImage before opening file");
        }
        lr.libraw_unpack(lrd);
        log.debug("unpacked " + (System.currentTimeMillis() - startTime));
    }
    /*
     * Copy the unprocessed data to temporary array so that we can restore 
     * lrd to the state it had after unpack()
     */

    int oldFlags = lrd.progress_flags;
    int oldFilters = lrd.idata.filters;
    int rawImageSize = lrd.sizes.iwidth * lrd.sizes.iheight * 4;
    short rawWidth = lrd.sizes.width;
    short rawHeight = lrd.sizes.height;
    this.width = lrd.sizes.width;
    this.height = lrd.sizes.height;
    short[] rawData = lrd.image.getShortArray(0, rawImageSize);
    lr.libraw_dcraw_process(lrd);
    log.debug("processed " + (System.currentTimeMillis() - startTime));
    int procWidth = lrd.sizes.width;
    int procHeight = lrd.sizes.height;

    int postSubsample = (lrd.output_params.half_size > 0) ? subsample / 2 : subsample;
    /*
     * Copy the raw image to Java raster, using box filter to subsample
     */
    int scaledW = procWidth / postSubsample;
    int scaledH = procHeight / postSubsample;
    short[] buf = new short[scaledW * scaledH * 3];
    int pos = 0;
    for (int row = 0; row < scaledH; row++) {
        for (int col = 0; col < scaledW; col++) {
            int rsum = 0;
            int gsum = 0;
            int bsum = 0;
            for (int or = row * postSubsample; or < (row + 1) * postSubsample; or++) {
                for (int oc = col * postSubsample; oc < (col + 1) * postSubsample; oc++) {
                    int r = lrd.image.getShort(8 * (oc + procWidth * or));
                    rsum += (r & 0xffff);
                    int g = lrd.image.getShort(8 * (oc + procWidth * or) + 2);
                    gsum += (g & 0xffff);
                    int b = lrd.image.getShort(8 * (oc + procWidth * or) + 4);
                    bsum += (b & 0xffff);
                }
            }
            buf[pos++] = (short) (rsum / (postSubsample * postSubsample));
            buf[pos++] = (short) (gsum / (postSubsample * postSubsample));
            buf[pos++] = (short) (bsum / (postSubsample * postSubsample));
        }
    }
    log.debug("subsampled " + (System.currentTimeMillis() - startTime));

    // Restore LibRaw state to what it was before dcraw_process
    lrd.image.write(0, rawData, 0, rawImageSize);
    lrd.progress_flags = oldFlags;
    lrd.sizes.width = rawWidth;
    lrd.sizes.height = rawHeight;
    lrd.idata.filters = oldFilters;
    rawData = null;

    // closeRaw();

    DataBuffer db = new DataBufferUShort(buf, buf.length);
    SampleModel sampleModel = RasterFactory.createPixelInterleavedSampleModel(DataBuffer.TYPE_USHORT, scaledW,
            scaledH, 3, 3 * scaledW, new int[] { 0, 1, 2 });
    WritableRaster r = Raster.createWritableRaster(sampleModel, db, new Point(0, 0));
    log.debug("raster created " + (System.currentTimeMillis() - startTime));

    if (this.chanMultipliers == null) {
        chanMultipliers = cameraMultipliers.clone();
        calcCTemp();
    }

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
    ColorModel targetCM = new ComponentColorModel(cs, new int[] { 16, 16, 16 }, false, false,
            Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
    rawImage = new TiledImage(new BufferedImage(targetCM, r, true, null), 256, 256);
    rawImage.setProperty("org.photovault.opname", "dcraw_data");

    if (preRotation.getJaiTransposeType() != null) {
        rawImage = TransposeDescriptor.create(rawImage, preRotation.getJaiTransposeType(), null);
        rawImage.setProperty("org.photovault.opname", "orientation_adjustment");
    }

    final float[] DEFAULT_KERNEL_1D = { 0.25f, 0.5f, 0.25f };
    ParameterBlock pb = new ParameterBlock();
    KernelJAI kernel = new KernelJAI(DEFAULT_KERNEL_1D.length, DEFAULT_KERNEL_1D.length,
            DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D, DEFAULT_KERNEL_1D);
    pb.add(kernel);
    BorderExtender extender = BorderExtender.createInstance(BorderExtender.BORDER_COPY);
    RenderingHints hints = JAI.getDefaultInstance().getRenderingHints();
    if (hints == null) {
        hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
    } else {
        hints.put(JAI.KEY_BORDER_EXTENDER, extender);
    }

    RenderedOp filter = new RenderedOp("convolve", pb, hints);
    // javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null );

    // Add the subsampling operation.
    pb = new ParameterBlock();
    pb.addSource(filter);
    pb.add(new Float(0.5F)).add(new Float(0.5F));
    pb.add(new Float(0.0F)).add(new Float(0.0F));
    pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
    RenderedOp downSampler = new RenderedOp("scale", pb, null);
    // downSampler = javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null );

    RenderableOp rawImageRenderable = RenderableDescriptor.createRenderable(rawImage, downSampler, null, null,
            null, null, null);
    double colorCorrMat[][] = new double[][] { { colorCorr[0], 0.0, 0.0, 0.0 }, { 0.0, colorCorr[1], 0.0, 0.0 },
            { 0.0, 0.0, colorCorr[2], 0.0 } };

    RenderingHints nonCachedHints = new RenderingHints(JAI.KEY_TILE_CACHE, null);
    wbAdjustedRawImage = BandCombineDescriptor.createRenderable(rawImageRenderable, colorCorrMat,
            nonCachedHints);
    wbAdjustedRawImage.setProperty("org.photovault.opname", "wb_adjusted_image");

    //            reader.getImageMetadata( 0 );
    //            rawIsHalfSized = dcraw.ishalfSize();
    //
    //            createHistogram();
    //        } catch (FileNotFoundException ex) {
    //            ex.printStackTrace();
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        } catch (PhotovaultException ex) {
    //            ex.printStackTrace();
    //        }
    log.debug("image ready " + (System.currentTimeMillis() - startTime));

    if (autoExposeRequested) {
        doAutoExpose();
    }
    log.debug("exit: loadRawImage " + (System.currentTimeMillis() - startTime));

}

From source file:org.photovault.swingui.ImageTile.java

/**
 * Draws the tile if it is found in cache. Otherwise, schedule a request
 * for computing it.//  w  ww .  ja va  2s.  c  o m
 * @param cache
 * @param g
 */
public void drawTile(TileCache cache, Graphics2D g) {
    Raster r = cache.getTile(img, tileX, tileY);
    if (r == null) {
        if (tileReq == null) {
            Point[] tileCoord = new Point[1];
            tileCoord[0] = new Point(tileX, tileY);
            tileReq = img.queueTiles(tileCoord);
        }
    } else {
        DataBuffer buf = r.getDataBuffer();
        SampleModel sm = r.getSampleModel();
        WritableRaster wr = Raster.createWritableRaster(sm, buf, new Point(0, 0));
        ColorModel cm = img.getColorModel();
        BufferedImage bufImg = new BufferedImage(cm, wr, false, null);
        g.drawImage(bufImg, null, tileX * tileWidth, tileY * tileHeight);
    }
}

From source file:org.shaman.terrain.polygonal.GraphToHeightmap.java

private void saveMatrix(float[][] matrix, String filename, float min, float max) {
    byte[] buffer = new byte[size * size];
    int i = 0;//  w ww .  ja  v  a2 s . c  o  m
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            buffer[i] = (byte) ((matrix[x][y] - min) * 255 / (max - min));
            i++;
        }
    }
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    int[] nBits = { 8 };
    ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    SampleModel sm = cm.createCompatibleSampleModel(size, size);
    DataBufferByte db = new DataBufferByte(buffer, size * size);
    WritableRaster raster = Raster.createWritableRaster(sm, db, null);
    BufferedImage result = new BufferedImage(cm, raster, false, null);
    try {
        ImageIO.write(result, "png", new File(filename));
    } catch (IOException ex) {
        Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.shaman.terrain.polygonal.GraphToHeightmap.java

private void saveColorMatrix(float[][][] matrix, String filename, float min, float max) {
    byte[] buffer = new byte[size * size * 3];
    int i = 0;//ww w . j  a v  a 2 s  .  co m
    for (int x = 0; x < size; ++x) {
        for (int y = 0; y < size; ++y) {
            buffer[i] = (byte) ((matrix[x][y][0] - min) * 255 / (max - min));
            i++;
            buffer[i] = (byte) ((matrix[x][y][1] - min) * 255 / (max - min));
            i++;
            buffer[i] = (byte) ((matrix[x][y][2] - min) * 255 / (max - min));
            i++;
        }
    }
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
    int[] nBits = { 8, 8, 8 };
    ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    SampleModel sm = cm.createCompatibleSampleModel(size, size);
    DataBufferByte db = new DataBufferByte(buffer, size * size * 3);
    WritableRaster raster = Raster.createWritableRaster(sm, db, null);
    BufferedImage result = new BufferedImage(cm, raster, false, null);
    try {
        ImageIO.write(result, "png", new File(filename));
    } catch (IOException ex) {
        Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex);
    }
}