Example usage for java.awt.image DataBufferInt getData

List of usage examples for java.awt.image DataBufferInt getData

Introduction

In this page you can find the example usage for java.awt.image DataBufferInt getData.

Prototype

public int[] getData() 

Source Link

Document

Returns the default (first) int data array in DataBuffer .

Usage

From source file:DataBufferGrabber.java

protected void paintComponent(Graphics g) {
    // create an image
    BufferedImage bImg = new BufferedImage(SWATCH_SIZE, SWATCH_SIZE, BufferedImage.TYPE_INT_RGB);
    Graphics gImage = bImg.getGraphics();
    gImage.setColor(Color.WHITE);
    gImage.fillRect(0, 0, SWATCH_SIZE, SWATCH_SIZE);

    // Time how long it takes to copy the managed version
    long managedTime = copyImage(g, bImg, 0, 0);
    System.out.println("Managed: " + managedTime + " ms");

    // Now grab the pixel array, change the colors, re-run the test
    Raster raster = bImg.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int pixels[] = dataBuffer.getData();
    for (int i = 0; i < pixels.length; ++i) {
        // Make all pixels black
        pixels[i] = 0;//from   www  .  jav a2s  .co m
    }

    // Time this un-managed copy
    long unmanagedTime = copyImage(g, bImg, SWATCH_SIZE, 0);
    System.out.println("Unmanaged: " + unmanagedTime + " ms");
}

From source file:com.neophob.sematrix.generator.Textwriter.java

/**
 * create image.//from   ww w .  j a v  a 2s  . c  om
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    maxXPos = (int) (0.5f + rect.getWidth()) + 5;
    ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB);
    g2 = img.createGraphics();

    g2.setColor(color);
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.drawString(text, xpos, ypos);
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    textBuffer = dbi.getData();
    g2.dispose();

    wait = 0;
    xofs = 0;
    scrollRight = false;
}

From source file:org.tsho.dmc2.core.chart.DmcLyapunovPlot.java

public boolean renderArea(Graphics2D g2, Rectangle2D dataArea) {

    CoreStatusEvent statusEv = new CoreStatusEvent(this);
    g2.setPaint(paint);/*from  w  w w  .  jav  a 2 s . c  o m*/

    final double parHStep, parVStep;
    double parHLower = domainAxis.getRange().getLowerBound();
    double parHUpper = domainAxis.getRange().getUpperBound();
    double parVLower = rangeAxis.getRange().getLowerBound();
    double parVUpper = rangeAxis.getRange().getUpperBound();

    parHStep = Math.abs(parHUpper - parHLower) / dataArea.getWidth();
    parVStep = Math.abs(parVUpper - parVLower) / dataArea.getHeight();

    final BufferedImage image = new BufferedImage((int) dataArea.getWidth(), (int) dataArea.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int[] data = dataBuffer.getData();

    final double parHStart = parHLower + parHStep / 2;
    final double parVStart = parVUpper - parVStep / 2;

    for (int i = 0; i < (int) dataArea.getWidth(); i++) {
        for (int j = 0; j < (int) dataArea.getHeight(); j++) {

            parameters.put(firstParLabel, parHStart + i * parHStep);
            parameters.put(secondParLabel, parVStart - j * parVStep);

            double[] result;
            int color;

            try {
                result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);
            } catch (ModelException e) {
                String mess = "Exception while:\n" + dumpVariableDoubles(parameters)
                        + dumpVariableDoubles(initialPoint);
                throw new ModelException(mess, e);
            }

            if (result == null) {
                System.out.println("i: " + i + " j: " + j);
                System.out.println("par1: " + parHStart + i * parHStep);
                System.out.println("par2: " + parVStart + j * parVStep);
                g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                statusEv.setStatusString("exception");
                statusEv.setType(CoreStatusEvent.STRING);
                notifyCoreStatusListeners(statusEv);
                return false;
            }

            // both zero
            if (Math.abs(result[0]) < epsilon && Math.abs(result[1]) < epsilon) {
                color = Color.black.getRGB();
            }
            // one zero one positive
            else if (Math.abs(result[0]) < epsilon && result[1] > 0
                    || Math.abs(result[1]) < epsilon && result[0] > 0) {
                color = Color.red.getRGB();
            }
            // one zero one negative
            else if (Math.abs(result[0]) < epsilon && result[1] < 0
                    || Math.abs(result[1]) < epsilon && result[0] < 0) {
                color = Color.blue.getRGB();
            }
            // one positive one negative
            else if (result[0] < 0 && result[1] > 0 || result[1] < 0 && result[0] > 0) {
                color = Color.green.getRGB();
            }
            // both positive
            else if (result[0] > 0 && result[1] > 0) {
                color = Color.orange.getRGB();
            }
            // both negative
            else if (result[0] < 0 && result[1] < 0) {
                color = Color.pink.getRGB();
            } else { // impossible
                color = Color.yellow.getRGB();
            }

            data[i + j * (int) dataArea.getWidth()] = color;

            if (stopped == true) {
                return false;
            }
            if (j == (int) dataArea.getHeight() - 1) {
                g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                statusEv.setPercent(0);
                statusEv.setType(CoreStatusEvent.COUNT | CoreStatusEvent.PERCENT);
                notifyCoreStatusListeners(statusEv);
            }
        }
    }

    return true;
}

From source file:org.tsho.dmc2.core.chart.LyapunovRenderer.java

public boolean renderArea(Graphics2D g2, Rectangle2D dataArea) {

    g2.setPaint(plot.paint);//from  w ww . ja  v  a2 s  .co m

    if (pass == 1) {
        if (image != null) {
            double x = dataArea.getX();
            double y = dataArea.getY();
            //there is a problem when using Graphics2D with affine transform 
            //and BufferedImage; using subclass of Image returned below.
            //rescaling needed because adding legend causes dataArea to change.
            Image scaledImage = image.getScaledInstance((int) dataArea.getWidth() - 1,
                    (int) dataArea.getHeight() - 1, Image.SCALE_DEFAULT);
            g2.drawImage(scaledImage, (int) x + 1, (int) y + 1, (int) dataArea.getWidth() - 1,
                    (int) dataArea.getHeight() - 1, this);
            //g2.translate(-1,-1);
            //g2.drawRect((int) x, (int) y, (int) dataArea.getWidth(),(int) dataArea.getHeight());
            //g2.translate(1,1);
        }
        return true;
    }

    final double parHStep, parVStep;
    double parHLower = plot.getDomainAxis().getRange().getLowerBound();
    double parHUpper = plot.getDomainAxis().getRange().getUpperBound();
    double parVLower = plot.getRangeAxis().getRange().getLowerBound();
    double parVUpper = plot.getRangeAxis().getRange().getUpperBound();

    parHStep = Math.abs(parHUpper - parHLower) / dataArea.getWidth();
    parVStep = Math.abs(parVUpper - parVLower) / dataArea.getHeight();

    image = new BufferedImage((int) dataArea.getWidth(), (int) dataArea.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    WritableRaster raster = image.getRaster();
    DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer();
    int[] data = dataBuffer.getData();

    final double parHStart = parHLower + parHStep / 2;
    final double parVStart = parVUpper - parVStep / 2;

    if (model instanceof ODE) {
        double step = stepSize; // stepSize and timeStep probably mean the same thing, one for discrete another for ODE
        double[] result = new double[model.getNVar()];

        for (int i = 0; i < (int) dataArea.getWidth(); i++) {
            for (int j = 0; j < (int) dataArea.getHeight(); j++) {

                parameters.put(firstParLabel, parHStart + i * parHStep);
                parameters.put(secondParLabel, parVStart - j * parVStep);

                int color;
                result = Lua.evaluateLyapunovExponentsODE(model, parameters, initialPoint, timePeriod,
                        stepSize);

                if (result == null) {
                    System.out.println("i: " + i + " j: " + j);
                    System.out.println("par1: " + parHStart + i * parHStep);
                    System.out.println("par2: " + parVStart + j * parVStep);
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                    return false;
                }

                int zer = 0;
                int pos = 0;
                int neg = 0;
                int nan = 0;
                for (int ii = 0; ii < result.length; ii++) {
                    if (Math.abs(result[ii]) == (1.0 / 0.0))
                        nan++;
                    else if (Math.abs(result[ii]) <= epsilon)
                        zer++;
                    else if (result[ii] > epsilon)
                        pos++;
                    else if (result[ii] < (-epsilon))
                        neg++;
                    else
                        nan++;
                }

                color = (lyapunovColors.getColor(zer, pos, neg, nan)).getRGB();
                ExpsSigns es = new ExpsSigns(zer, pos, neg, nan);
                if (!signsSet.contains(es))
                    signsSet.add(es);

                data[i + j * (int) dataArea.getWidth()] = color;

                if (stopped == true)
                    return false;

                if (j == (int) dataArea.getHeight() - 1) {
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                }
            } //end for
        } //end for
    } //end if ODE
    else {
        for (int i = 0; i < (int) dataArea.getWidth(); i++) {
            for (int j = 0; j < (int) dataArea.getHeight(); j++) {

                parameters.put(firstParLabel, parHStart + i * parHStep);
                parameters.put(secondParLabel, parVStart - j * parVStep);

                double[] result;
                int color;

                result = Lua.evaluateLyapunovExponents(model, parameters, initialPoint, iterations);

                if (result == null) {
                    System.out.println("i: " + i + " j: " + j);
                    System.out.println("par1: " + parHStart + i * parHStep);
                    System.out.println("par2: " + parVStart + j * parVStep);
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
                    return false;
                }

                int zer = 0;
                int pos = 0;
                int neg = 0;
                int nan = 0;
                for (int ii = 0; ii < result.length; ii++) {
                    if (Math.abs(result[ii]) == (1.0 / 0.0))
                        nan++;
                    else if (Math.abs(result[ii]) <= epsilon)
                        zer++;
                    else if (result[ii] > epsilon)
                        pos++;
                    else if (result[ii] < (-epsilon))
                        neg++;
                    else
                        nan++;
                }

                color = (lyapunovColors.getColor(zer, pos, neg, nan)).getRGB();
                ExpsSigns es = new ExpsSigns(zer, pos, neg, nan);
                if (!signsSet.contains(es))
                    signsSet.add(es);

                data[i + j * (int) dataArea.getWidth()] = color;

                if (stopped == true)
                    return false;

                if (j == (int) dataArea.getHeight() - 1)
                    g2.drawImage(image, null, (int) dataArea.getX() + 1, (int) dataArea.getY() + 1);
            } //end for
        } //end for
    } //end else
    return true;
}

From source file:org.apache.fop.render.pdf.pdfbox.PSPDFGraphics2D.java

@Override
public boolean drawImage(Image img, int x1, int y1, ImageObserver observer) {
    PSGenerator tmp = gen;/* w  w w  . j  av  a  2s.  c o  m*/
    if (gen instanceof PSDocumentHandler.FOPPSGenerator) {
        PSDocumentHandler.FOPPSGenerator fopGen = (PSDocumentHandler.FOPPSGenerator) tmp;
        PSDocumentHandler handler = fopGen.getHandler();
        if (handler.getPSUtil().isOptimizeResources()) {
            try {
                final int width = img.getWidth(observer);
                final int height = img.getHeight(observer);
                if (width == -1 || height == -1) {
                    return false;
                }
                BufferedImage buf = getImage(width, height, img, observer);
                if (buf == null) {
                    return false;
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                DataBufferInt db = (DataBufferInt) buf.getRaster().getDataBuffer();
                DataOutputStream dos = new DataOutputStream(bos);
                dos.writeInt(width);
                dos.writeInt(height);
                for (int i : db.getData()) {
                    dos.writeInt(i);
                }
                String format = DataBufferInt.class.getName();
                int hash = Arrays.hashCode(bos.toByteArray());
                URI uri = fopGen.getImages().get(hash);
                if (uri == null) {
                    uri = new TempResourceURIGenerator("img" + hash + "." + format).generate();
                    fopGen.getImages().put(hash, uri);
                    BufferedOutputStream outputStream = fopGen.getTempStream(uri);
                    outputStream.write(bos.toByteArray());
                    outputStream.close();
                }
                PSResource form = handler.getFormForImage(uri.toASCIIString());
                ImageInfo info = new ImageInfo(uri.toASCIIString(), "image/" + format);
                ImageSize size = new ImageSize(width, height, handler.getUserAgent().getTargetResolution());
                size.calcSizeFromPixels();
                info.setSize(size);
                float res = handler.getUserAgent().getSourceResolution() / 72;
                Rectangle rect = new Rectangle(0, 0, (int) (size.getWidthMpt() * res),
                        (int) (size.getHeightMpt() * res));
                gen.saveGraphicsState();
                gen.concatMatrix(getTransform());
                writeClip(getClip());
                PSImageUtils.drawForm(form, info, rect, gen);
                gen.restoreGraphicsState();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    }
    return super.drawImage(img, x1, y1, observer);
}

From source file:se.llbit.chunky.renderer.cl.CLRenderManager.java

private void updateCanvas(float[] samples) {
    try {//from  www. ja  va 2s  . c om
        synchronized (buffer) {
            DataBufferInt dataBuffer = (DataBufferInt) backBuffer.getRaster().getDataBuffer();
            int[] imgData = dataBuffer.getData();

            // paint the back buffer
            for (int i = 0; i < bufferWidth * bufferHeight; ++i) {
                imgData[i] = Color.getRGB(QuickMath.min(1, FastMath.pow(samples[i * 3], 1 / 2.2)),
                        QuickMath.min(1, FastMath.pow(samples[i * 3 + 1], 1 / 2.2)),
                        QuickMath.min(1, FastMath.pow(samples[i * 3 + 2], 1 / 2.2)));
            }

            // flip buffers
            BufferedImage tmp = buffer;
            buffer = backBuffer;
            backBuffer = tmp;
        }
        view.getCanvas().repaint();
    } catch (IllegalStateException e) {
        Log.error("Unexpected exception while rendering back buffer", e);
    }
}

From source file:se.llbit.chunky.resources.Texture.java

public void setTexture(BufferedImage newImage) {
    if (newImage.getType() == BufferedImage.TYPE_INT_ARGB) {
        image = newImage;//  w  ww  .ja va 2  s.c om
    } else {
        // convert to ARGB
        image = new BufferedImage(newImage.getWidth(), newImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.createGraphics();
        g.drawImage(newImage, 0, 0, null);
        g.dispose();
    }

    // gamma correct the texture
    avgColorLinear = new float[] { 0, 0, 0, 0 };

    DataBufferInt dataBuffer = (DataBufferInt) image.getRaster().getDataBuffer();
    int[] data = dataBuffer.getData();
    width = image.getWidth();
    height = image.getHeight();
    linear = new float[width * height][4];
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            int index = width * y + x;
            Color.getRGBAComponents(data[index], linear[index]);
            linear[index][0] = (float) FastMath.pow(linear[index][0], Scene.DEFAULT_GAMMA);
            linear[index][1] = (float) FastMath.pow(linear[index][1], Scene.DEFAULT_GAMMA);
            linear[index][2] = (float) FastMath.pow(linear[index][2], Scene.DEFAULT_GAMMA);
            avgColorLinear[0] += linear[index][3] * linear[index][0];
            avgColorLinear[1] += linear[index][3] * linear[index][1];
            avgColorLinear[2] += linear[index][3] * linear[index][2];
            avgColorLinear[3] += linear[index][3];
        }
    }

    if (PersistentSettings.getSingleColorTextures()) {
        float[] avgColorFlat = { 0, 0, 0 };
        if (avgColorLinear[3] > 0.001) {
            avgColorFlat[0] = avgColorLinear[0] / avgColorLinear[3];
            avgColorFlat[1] = avgColorLinear[1] / avgColorLinear[3];
            avgColorFlat[2] = avgColorLinear[2] / avgColorLinear[3];
        }
        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                int index = width * y + x;
                linear[index][0] = avgColorFlat[0];
                linear[index][1] = avgColorFlat[1];
                linear[index][2] = avgColorFlat[2];
                linear[index][3] = 1;
            }
        }
    }

    avgColorLinear[0] /= width * height;
    avgColorLinear[1] /= width * height;
    avgColorLinear[2] /= width * height;
    avgColorLinear[3] /= width * height;

    avgColor = Color.getRGBA(FastMath.pow(avgColorLinear[0], 1 / Scene.DEFAULT_GAMMA),
            FastMath.pow(avgColorLinear[1], 1 / Scene.DEFAULT_GAMMA),
            FastMath.pow(avgColorLinear[2], 1 / Scene.DEFAULT_GAMMA), avgColorLinear[3]);
}

From source file:se.llbit.chunky.world.SkymapTexture.java

@Override
public void setTexture(BufferedImage newImage) {

    if (newImage.getType() == BufferedImage.TYPE_INT_ARGB) {
        image = newImage;//w w w. j  a  v a  2 s. c  om
    } else {
        // convert to ARGB
        image = new BufferedImage(newImage.getWidth(), newImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.createGraphics();
        g.drawImage(newImage, 0, 0, null);
        g.dispose();
    }

    DataBufferInt dataBuffer = (DataBufferInt) image.getRaster().getDataBuffer();
    data = dataBuffer.getData();

    width = image.getWidth();
    height = image.getHeight();
    avgColor = ImageTools.calcAvgColor(image);

    Log.info("Preprocessing skymap texture");
    long start = System.currentTimeMillis();

    // gamma correct the texture

    int segX = 4;
    int segY = 4;
    if (width < segX)
        segX = 1;
    if (height < segY)
        segY = 1;
    TexturePreprocessor[][] preprocessor = new TexturePreprocessor[segX][segY];
    int w = width / segX;
    int h = height / segY;
    for (int i = 0; i < segX; ++i) {
        int x0 = w * i;
        int x1 = x0 + w - 1;
        if ((i + 1) == segX)
            x1 = width - 1;
        for (int j = 0; j < segY; ++j) {
            int y0 = h * j;
            int y1 = y0 + h - 1;
            if ((j + 1) == segY)
                y1 = height - 1;
            preprocessor[i][j] = new TexturePreprocessor(x0, x1, y0, y1);
            preprocessor[i][j].start();
        }
    }

    for (int i = 0; i < segX; ++i) {
        for (int j = 0; j < segY; ++j) {
            try {
                preprocessor[i][j].join();
            } catch (InterruptedException e) {
            }
        }
    }

    long time = System.currentTimeMillis() - start;

    Log.info("Skymap preprocessing took " + time + "ms");

}

From source file:VASSAL.tools.image.tilecache.TileUtils.java

/**
 * Reads an image tile./*  w  w w . j a v a2 s. c  o  m*/
 *
 * @param in a stream containing the tile data
 * @return the tile image
 *
 * @throws IOException if the read fails
 */
public static BufferedImage read(InputStream in) throws IOException {
    ByteBuffer bb;

    // read the header
    final byte[] header = readHeader(in);
    bb = ByteBuffer.wrap(header);

    // validate the signature
    final byte[] sig = new byte[6];
    bb.get(sig);
    checkSignature(sig);

    // get the dimensions and type
    final int w = bb.getInt();
    final int h = bb.getInt();
    final int type = bb.getInt();

    // read the image data
    final byte[] cdata = IOUtils.toByteArray(in);

    // decompress the image data
    InputStream zin = null;
    try {
        zin = new GZIPInputStream(new ByteArrayInputStream(cdata));
        bb = ByteBuffer.wrap(IOUtils.toByteArray(zin));
        zin.close();
    } finally {
        IOUtils.closeQuietly(zin);
    }

    // build the image
    final BufferedImage img = new BufferedImage(w, h, type);

    // FIXME: This might decelerate the image? If so, then we should
    // make a copy.
    final DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer();
    final int[] data = db.getData();

    final IntBuffer ib = bb.asIntBuffer();
    ib.get(data);

    /*
        if (ib.hasRemaining()) {
          // buffer contains garbage at the end!
          throw new IOException("found " + (4*ib.remaining()) + " more bytes!");
        }
    */

    return img;
}

From source file:VASSAL.tools.image.tilecache.TileUtils.java

/**
 * Write a tile image to a stream./*from   w w  w . j  a  v a  2s.  co  m*/
 *
 * @param tile the image
 * @param out the stream
 *
 * @throws ImageIOException if the write fails
 */
public static void write(BufferedImage tile, OutputStream out) throws IOException {
    ByteBuffer bb;

    // write the header
    bb = ByteBuffer.allocate(18);

    bb.put("VASSAL".getBytes()).putInt(tile.getWidth()).putInt(tile.getHeight()).putInt(tile.getType());

    out.write(bb.array());

    // write the tile data
    final DataBufferInt db = (DataBufferInt) tile.getRaster().getDataBuffer();
    final int[] data = db.getData();

    bb = ByteBuffer.allocate(4 * data.length);
    bb.asIntBuffer().put(data);

    final GZIPOutputStream zout = new GZIPOutputStream(out);
    zout.write(bb.array());
    zout.finish();
}