Filling in quadrilaterals in a pixel array

Short version: Does anyone know of an algorithm like fillPolygon, but that works with a pixel array? (and doesn't need more than v1.1) Thanks.
Long version:
Hi. Hope there's a math guru among you who can give me a clue...
I'm doing an animated 3D applet but restricted to pre-plugin Java - nothing post about 1.1. I'm double buffering for speed, with an int array [screenwidth*screenheight] for the pixels.
At the start of each frame I want to colour in the areas where some flat rectangles (walls) are as the 'camera' sees them - quadrilaterals whose corners could be anywhere on or off the screen.
For each line of the quadrilateral I can figure out how to find the on-screen start and end points - stopping where either the line or the screen stops, but I can't think of a fast algorithm to get from those 8 numbers per wall to a correctly filled-in pixel array.
Thanks for your help.

As your quadrilaterals are transformed rectangles,
they should also be convex.
From one vertex, with the most extreem ordiante in a
chosen direction (eg the left-most) iterate in one
direction (eg +ve x) along the two edges to the
adjacent vertices using Bresenham's algorithm. That
will give you two points with a common ordinate (eg
(x, y0(x)) and (x, y1(x))), between which you may
fill a line.
On encountering another vertex, continue iterating
along the next edge until the next vertex. When the
furthest vertex is reached, you have filled your
convex quadrilateral.
Petethis approach is just fine and about as fast as you can get.
another approach is filling the qualiteral (works as well for any convex
polygon) by means of a triangle fan ...
so for quadliteral with vertices A, B, C, D (each having x and y copmonents) you draw a triangle fan around a pivot point (lets say that is vertex A) like this
drawTri (A, B, C)
drawTri (A, C, D)
or for a 5 vertex polygon (A, B, C, D, E)it would be
drawTri (A, B, C)
drawTri (A, C, D)
drawTri (A, D, E)
this works just as well, with a few minor advantages and disadvantages ...

Similar Messages

  • Only writing Integer pixel array to a .txt file,or showing in Frame

    Sir,
    I want to write integer values (range:0 to 255) to a .txt file .Actually after manipulating a .jpeg/.gif image I have gotten a 2D pixel array and a 1D pixel array that can be easily shown in console but I want to write this pixel array into a .txt file. Using of writeInt() is not working. Actually after using this faction the created file contain information which is non-alphanumeric /alphanumeric characters......
    following is error free the code: Plz. See only and only into the �class TestImage�and plz look after line marked by //�my_problem_to_be_resolved.�It is just few lines of code .I promise you will not be bothered.Plz��..
    import java.awt.*;
    import java.io.File;
    import java.io.FileWriter;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.awt.image.Raster;
    import java.awt.image.WritableRaster;
    class Image {
    protected int width,height;
    // 'samples' stores the image pixel values.
    protected int[][] samples;
    // Constructor: Reads the image from the
    // specified file name.
    public Image(String filename)
    throws Exception { read(filename); }
    // Returns the pixel width of the image.
    public int getWidth() { return width; }
    // Returns the pixel height of the image.
    public int getHeight() { return height; }
    // Reads the image from the specified file
    // name into the 'samples' array. Throws an
    // exception if the image is stored in an
    // unsupported file format (currently only
    // .GIF, .JPG, and .PNG are supported by Sun).
    public void read(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageReaders that claim
    // to be able to decode this image file
    // based on the file name suffix.
    Iterator imageReaders = ImageIO.
    getImageReadersBySuffix(ext);
    ImageReader imageReader;
    // Grab the first ImageReader in the list.
    if (imageReaders.hasNext())
    imageReader = (ImageReader)
    imageReaders.next();
    // If we get here we cannot decode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file input stream object to
    // read the image date.
    FileImageInputStream imageInputStream =
    new FileImageInputStream(fileImage);
    // Tell the ImageReader object to read data
    // from our file input stream object.
    imageReader.setInput(imageInputStream);
    // Get the width and height of the image.
    width = imageReader.getWidth(0);
    height = imageReader.getHeight(0);
    // Read the image from the file input stream,
    // and close the input stream when done.
    BufferedImage bufImage =
    imageReader.read(0);
    imageInputStream.close();
    // Get a raster object so we can extract the
    // pixel data from the BufferedImage.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Create our 'samples' 2d-array.
    samples = new int[height][width];
    // Extract the image data into our 'samples'
    // array.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    samples[row][col] =
    wRaster.getSample(col,row,0);
    // Write the image stored in the 'samples'
    // array to the specified file. The file name
    // suffix should be a supported image file
    // format (currently either .JPG or .PNG).
    public void write(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageWriters that claim to
    // be able to encode images in the specified
    // image file format based on the file name
    // suffix.
    Iterator imageWriters = ImageIO.
    getImageWritersBySuffix(ext);
    ImageWriter imageWriter;
    // Grab the first ImageWriter in the list.
    if (imageWriters.hasNext())
    imageWriter = (ImageWriter)
    imageWriters.next();
    // If we get here we cannot encode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file output stream object to
    // write the image data.
    FileImageOutputStream imageOutputStream
    = new FileImageOutputStream
    (fileImage);
    // Tell the ImageWriter to use our file
    // output stream object.
    imageWriter.setOutput
    (imageOutputStream);
    // The ImageWriter.write() method expects a
    // BufferedImage. Convert our 'samples' array
    // into a BufferedImage.
    BufferedImage bufImage =
    createBufferedImage();
    // Encode the image to the output file.
    imageWriter.write(bufImage);
    imageOutputStream.close();
    // Draws the image stored in the 'samples'
    // array on the specified graphics context.
    public void draw(Graphics gc,int x,int y){
    BufferedImage bufImage =
    createBufferedImage();
    gc.drawImage(bufImage,x,y,null);
    // Converts the 'samples' array into a
    // BufferedImage object. Students do not have
    // to understand how this works.
    private BufferedImage
    createBufferedImage() {
    // Create a monochrome BufferedImage object.
    BufferedImage bufImage = new
    BufferedImage(width,height,
    BufferedImage.TYPE_BYTE_GRAY);
    // Create a WriteableRaster object so we can
    // put sample data into the BufferedImage
    // object's raster.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Copy the 'samples' data into the
    // BufferedImage object's raster.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    wRaster.setSample
    (col,row,0,samples[row][col]);
    // Return the newly created BufferedImage.
    return bufImage;
    } // End of Class Image
    class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("C:/lilies.jpg");
    int height=img.getHeight();
    int width =img.getWidth();
    //�my_problem_to_be_resolved.�
         File image_object_arry=new File("C:/Image_array.txt");
         FileOutputStream image_object_arry_stream= new FileOutputStream(image_object_arry);
         DataOutputStream int_image_object_arry_stream=new DataOutputStream(image_object_arry_stream);
    //Conversion of two dimensional pixel arrry into one dimensional array
    int intPixels1[] = new int [height * width];
    int k = 0;
    for(int i = 0; i <= width; i++) {
    for(int j = 0; j <= height; j++) {
    intPixels1[k] = img.samples[i][j];
    int_image_object_arry_stream.writeInt((int) intPixels1[k]);
    // System.out.println(intPixels1[k]);
    k = k+1;
    import java.awt.*;
    import java.io.File;
    import java.io.FileWriter;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.awt.image.Raster;
    import java.awt.image.WritableRaster;
    class Image {
    protected int width,height;
    // 'samples' stores the image pixel values.
    protected int[][] samples;
    // Constructor: Reads the image from the
    // specified file name.
    public Image(String filename)
    throws Exception { read(filename); }
    // Returns the pixel width of the image.
    public int getWidth() { return width; }
    // Returns the pixel height of the image.
    public int getHeight() { return height; }
    // Reads the image from the specified file
    // name into the 'samples' array. Throws an
    // exception if the image is stored in an
    // unsupported file format (currently only
    // .GIF, .JPG, and .PNG are supported by Sun).
    public void read(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageReaders that claim
    // to be able to decode this image file
    // based on the file name suffix.
    Iterator imageReaders = ImageIO.
    getImageReadersBySuffix(ext);
    ImageReader imageReader;
    // Grab the first ImageReader in the list.
    if (imageReaders.hasNext())
    imageReader = (ImageReader)
    imageReaders.next();
    // If we get here we cannot decode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file input stream object to
    // read the image date.
    FileImageInputStream imageInputStream =
    new FileImageInputStream(fileImage);
    // Tell the ImageReader object to read data
    // from our file input stream object.
    imageReader.setInput(imageInputStream);
    // Get the width and height of the image.
    width = imageReader.getWidth(0);
    height = imageReader.getHeight(0);
    // Read the image from the file input stream,
    // and close the input stream when done.
    BufferedImage bufImage =
    imageReader.read(0);
    imageInputStream.close();
    // Get a raster object so we can extract the
    // pixel data from the BufferedImage.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Create our 'samples' 2d-array.
    samples = new int[height][width];
    // Extract the image data into our 'samples'
    // array.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    samples[row][col] =
    wRaster.getSample(col,row,0);
    // Write the image stored in the 'samples'
    // array to the specified file. The file name
    // suffix should be a supported image file
    // format (currently either .JPG or .PNG).
    public void write(String filename)
    throws Exception {
    // Extract the file name suffix.
    String ext = filename.substring
    (filename.indexOf('.')+1);
    // Create a file object for the file name.
    File fileImage = new File(filename);
    // Get a list of ImageWriters that claim to
    // be able to encode images in the specified
    // image file format based on the file name
    // suffix.
    Iterator imageWriters = ImageIO.
    getImageWritersBySuffix(ext);
    ImageWriter imageWriter;
    // Grab the first ImageWriter in the list.
    if (imageWriters.hasNext())
    imageWriter = (ImageWriter)
    imageWriters.next();
    // If we get here we cannot encode the image.
    else throw new IIOException
    ("Unsupported image format");
    // Create a file output stream object to
    // write the image data.
    FileImageOutputStream imageOutputStream
    = new FileImageOutputStream
    (fileImage);
    // Tell the ImageWriter to use our file
    // output stream object.
    imageWriter.setOutput
    (imageOutputStream);
    // The ImageWriter.write() method expects a
    // BufferedImage. Convert our 'samples' array
    // into a BufferedImage.
    BufferedImage bufImage =
    createBufferedImage();
    // Encode the image to the output file.
    imageWriter.write(bufImage);
    imageOutputStream.close();
    // Draws the image stored in the 'samples'
    // array on the specified graphics context.
    public void draw(Graphics gc,int x,int y){
    BufferedImage bufImage =
    createBufferedImage();
    gc.drawImage(bufImage,x,y,null);
    // Converts the 'samples' array into a
    // BufferedImage object. Students do not have
    // to understand how this works.
    private BufferedImage
    createBufferedImage() {
    // Create a monochrome BufferedImage object.
    BufferedImage bufImage = new
    BufferedImage(width,height,
    BufferedImage.TYPE_BYTE_GRAY);
    // Create a WriteableRaster object so we can
    // put sample data into the BufferedImage
    // object's raster.
    WritableRaster wRaster =
    bufImage.getRaster();
    // Copy the 'samples' data into the
    // BufferedImage object's raster.
    for (int row = 0; row < height; row++)
    for (int col = 0; col < width; col++)
    wRaster.setSample
    (col,row,0,samples[row][col]);
    // Return the newly created BufferedImage.
    return bufImage;
    } // End of Class Image
    /*class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("C:/srk.jpg");
    // Display the image.
    img.draw(gc,10,40);
    // Flip the image upside down
    //img.flipX();
    // Display the flipped image.
    img.draw(gc,20+img.getWidth(),40);
    // Write the new image to a file
    img.write("HorseNew.jpg");
    } catch (Exception e) {
    System.out.println
    ("Exception in main() "+e.toString());
    class TestImage {
    public static void main(String args[])
    throws Exception {
    // Create a frame to display the image.
    Frame frame = new Frame("Test Image");
    frame.setSize(1024,768);
    frame.setVisible(true);
    Graphics gc = frame.getGraphics();
    try {
    // Read the image from the file.
    Image img = new Image("C:/lilies.jpg");
    int height=img.getHeight();
    int width =img.getWidth();
    File image_object_arry=new File("C:/Image_array.txt");
    FileOutputStream image_object_arry_stream=new FileOutputStream(image_object_arry);
         DataOutputStream int_image_object_arry_stream=new DataOutputStream(image_object_arry_stream);
    //Conversion of two dimensional pixel arrry into one dimensional array
    int intPixels1[] = new int [height * width];
    int k = 0;
    for(int i = 0; i <= width; i++) {
    for(int j = 0; j <= height; j++) {
    intPixels1[k] = img.samples[i][j];
    int_image_object_arry_stream.writeInt((int) intPixels1[k]);
    // System.out.println(intPixels1[k]);
    k = k+1;
    catch (Exception e) {
    System.out.println("Exception in main() "+e.toString());
    catch (Exception e) {
    System.out.println("Exception in main() "+e.toString());
    }

    My Friend, you need to put your code within CODE tags
    And I suspect if anyone would go through your code this way.
    Assuming your problem is to write pixel values to a file you may use this,
          try{
            // Create file
            FileWriter fstream = new FileWriter("out.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            for(int i =0; pixels.length() ; i++)
              out.write(pixels[i]+"\t");
           //Close the output stream
           out.close();
           }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }

  • I am trying to make a call to a dll to have labview return a buffer filled with data stored in an array. The proble

    m that I am having is that to do this I need to fill two different structures, one containing a pointer to a double, which I don't think I can do without perhaps a wrapper function. The biggest problem is that I don't know how to even go about doing this.I have two structures that I need to fill in order to read a block of data from a given DLL which are
    typedef struct CHBL_ORDER_T {
    INT32 lBlock; // block number, set by user (typical 0)
    INT16 sChan; // channel number, set by user
    UINT16 usFlags; // only DATA_1OFN at the moment
    INT32 lChSR; // channel sampling rate, returned by open
    INT32 lFirstMP; // BSR MP not greater than "open sta
    rt"
    INT32 lBuffLen; // required CHSR based buffer size
    INT32 lIncr; // distance between two buffered values
    UINT16 usMask; // Mask used before Shift
    INT8 chShift; // number of right shifts
    } CHBL_ORDER, *PCHBL_ORDER;
    typedef struct CHBL_FETCH_T {
    double *pdblMin; // min or 1 of n array
    double *pdblMax; // max array (either solo or along with MINMAX
    INT32 lPos; // (set by user), returned by fetch
    INT32 lNum; // (set by user), returned by fetch
    } CHBL_FETCH, *PCHBL_FETCH;
    I am trying to do the data block access with labview on page 18 of the attached pdf document.
    I also have a c code exapmle attached in the zip file, the function in c i am trying to do is in Sample2Dlg.cpp
    if anyone can help me out I would greatly appreciate it.
    Attachments:
    BS_Toolbox_(Ford).PDF ‏160 KB
    sample2.zip ‏55 KB

    m that I am having is that to do this I need to fill two different structures, one containing a pointer to a double, which I don't think I can do without perhaps a wrapper function. The biggest problem is that I don't know how to even go about doing this.I believe you are right about needing to create a wrapper DLL. To do this, just create a DLL which includes a function that accepts a double. Then, it uses this to make a pointer to that double and send it to your original DLL. When that function returns, you return this info to LabVIEW in form of a regular double. Basically, there is just one more layer of code which you use for translation between LabVIEW and the DLL you are currently using. You need to create that layer.
    J.R. Allen

  • Trouble writing pixel array back to gif file

    Hi everyone. I am in the middle of constructing a steganography api for a final year group project. I have taken out the pixels into an array from a gif file. I am having trouble writing it back to a gif file. Here is my code:
    import javaSteg.stegoLibrary.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import Acme.*;
    import Acme.JPM.Encoders.*;
    public class Gif extends Canvas{
         public void encodeGif(byte[] imageData){
              //create toolkit obarrayPointerect
              Toolkit t = Toolkit.getDefaultToolkit();
              MediaTracker tracker = new MediaTracker(this);
              //decode specified Gif cover
              Image img = t.createImage(imageData);      
              tracker.addImage(img,0);
              try{
                   tracker.waitForAll();
              catch(InterruptedException e){
              System.out.println("Tracker interrupted.");
              //retrive picture from image
              int[] pix = new int[img.getWidth(this) * img.getHeight(this)];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(this), img.getHeight(this), pix, 0, img.getWidth(this));
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              return;
              //put into byte array
              byte[] pixels = new byte[img.getWidth(this) * img.getHeight(this)];     
              for(int arrayPointer=0;arrayPointer<pix.length;arrayPointer++){
                   pixels[arrayPointer] = new Integer(pix[arrayPointer]).byteValue();
              //edit pixels not implemented yet
    //assign edited pixels to an image
              img = t.createImage(pixels);
              // Now encode the image using ACME free GIF encoder (www.acme.com)
              try{
                   FileOutputStream fos = new FileOutputStream("D:\\result.gif");
                   GifEncoder encoder = new GifEncoder(img, fos);
                   encoder.encode();
                   fos.close();
              }catch(IOException e) {
              System.out.println("FATAL IOException "+e);
    From this i get a single pixel in my output gif file. Is there a way of swapping out the edited pixels with the origonal pixels in the image file? or an alternative way to write back the complete file.
    Thanks a lot
    MickyT

    ive managed to solve it. For those who come across this thread and want to know the solution i needed to use MemoryImageSource with the pixels inorder to pass them to the createImage method :o)

  • Photoshop opens dialog box when trying to fill a layer with transparent pixels locked

    This script should set the layer to lock transparent pixels, and then fill the layer with a color. It does that, except when it gets to the fill stage, it opens the fill dialog box, and you have to hit okay.
    If you omit the transparent pixel line, it runs as expected, no dialog box.
    Is there a way to suppress the box? Or am I doing something wrong that's causing the box to open?
    #target photoshop
    app.bringToFront();
    doc = app.activeDocument;
    doc.artLayers[0].isBackgroundLayer = false;
    doc.artLayers[0].transparentPixelsLocked = true;
    app.activeDocument.selection.fill(app.foregroundColor);

    Not sure why that happens.
    But I would recommend foregoing the locking and using the AM code for a Fill that honours the transparency.
    #target photoshop 
    app.bringToFront(); 
    doc = app.activeDocument; 
    doc.artLayers[0].isBackgroundLayer = false; 
    doc.activeLayer = doc.artLayers[0];
    // =======================================================
    var idFl = charIDToTypeID( "Fl  " );
        var desc18 = new ActionDescriptor();
        var idUsng = charIDToTypeID( "Usng" );
        var idFlCn = charIDToTypeID( "FlCn" );
        var idFrgC = charIDToTypeID( "FrgC" );
        desc18.putEnumerated( idUsng, idFlCn, idFrgC );
        var idOpct = charIDToTypeID( "Opct" );
        var idPrc = charIDToTypeID( "#Prc" );
        desc18.putUnitDouble( idOpct, idPrc, 100.000000 );
        var idMd = charIDToTypeID( "Md  " );
        var idBlnM = charIDToTypeID( "BlnM" );
        var idNrml = charIDToTypeID( "Nrml" );
        desc18.putEnumerated( idMd, idBlnM, idNrml );
        var idPrsT = charIDToTypeID( "PrsT" );
        desc18.putBoolean( idPrsT, true );
    executeAction( idFl, desc18, DialogModes.NO );

  • How to fill or erase a single pixel?

    What tool or tools do I have to use to erase or fill a single pixel at a time?
    Sincere thanks in advance for yourhelp.
    Al

    So many ways; you can use one or a combination of:
    Brush Tool set to 1 pixel and a color that matches the area
    Spot Healing Brush Tool set to around 3 or 4 pixels
    Clone Stamp Tool set to a reasonable size based upon area and a soft edge (a graphics tablet like those from Wacom is a big help here due to being able to set size and opacity; pen pressure determines size and/or opacity as you paint)

  • Fill method isn't working on arrays.

    I am trying to use(on JDK 1.4) the fill method of util.Arrays class to fill an array. It gives "cannot resolve symbol" error at the line with fill command. What am I doing wrong here ?
    import java.util.Arrays;
    public class arrtest {
    public static void main(String[] args)
    int arr[] = new int[20];
    fill(arr,0,7,1);
    }}

    The fill() method is a static member of the Arrays
    class and hence must be identified as such. Try
    substituting the following line for what you already
    have:
    Arrays.fill(arr, 0, 7, 1);ShaunYup.
    Thanks Shaun.

  • Quick Question on Arrays.fill() Method

    Does this work for a multidimensional array? I've tried and I can't get it to.
              double stuGrade[][];
              stuGrade = new double[3][125];
              Arrays.fill(stuGrade, -1); //Have also tried Arrays.fill(stuGrade[][], -1) error: Cannot resolve symbol
    symbol: method fill (double, int)
    Have imported java.util.Arrays....
    I need to set all values in atleast one row to a negative number. I haven't had a chance to look at vector (is that it?) arrays. So every element may not be populated. Since it is possible for an entry to be zero, I can't use a condition of not equal to zero to determine whether the loop should continue processing or not....
    Thank you!

    fill(double[] a, int fromIndex, int toIndex, double
    val)
    Where a is your array.... so really your just missing
    your fromIndex and toIndex... no worries.Seeing as how the OP's array is a double[][] rather than a double[], the worries will continue. The fromIndex and toIndex are optional; if he's wanting to fill a single entire array, the fill(double[] a, double val) is fine.

  • How to fill a javascript array by a jsp array when the jsp is run

    Hi all,
    The problem i am facing is -- i want to use an javascript array in a function. The records are being fetched by jsp.
    How to fill the vaules in a javascript array, which are retrieved by a jsp array
    Please suggest
    Thanking You

    You can use the code below:
    <input type="button" value="Click Me" onclick="javascript:disp('<%= getString(str) %>')">
    <%!
    public String getString(String str[]){
    String arrElements="";
    for(int i=0;i<str.length;i++) {
    arrElements+=str[i]+",";
    return arrElements.substring(0,arrElements.length()-1);
    %>
    function disp(str) {
    arr = str.split(",");
    alert ("There are "+arr.length+" elements in the array");
    Hope this helps.

  • Binary fill doesn't work

    Hi,
    Trying to fill the holes when appearing in binary images.
    I have this code which seems to fall into an infinate loop:
    int [][] arrImage (byte [][] input) {
        int xe = input[0].length;
        int ye = input.length;
        int [][] output = new int[xe][ye];
        int [][] pixel =  new int[xe][ye];
        int x;
        int y;
        boolean b;
        for(y=0;y<ye;y++) {
            for (x = 0; x < xe; x++) {
                pixel[x][y] = input[y][x] & 0xff;
        for (y=0; y<ye; y++){
          if((input[y][0]& 0xff)==0)
            output[0][y] = 255;  
          if((input[y][xe-1]& 0xff) == 0)
            output[xe-1][y] = 255;
        for (x=0; x<xe; x++){
          if((input[0][x]& 0xff) == 0)
            output[x][0] = 255;
          if((input[ye-1][x]& 0xff) == 0)
            output[x][ye-1] = 255;
                    b=true;
                    while(b){
                        b=false;
                        for(y=1;y<ye-1;y++) {
                            for(x=1;x<xe-1;x++) {
                                if ((input[y][x]& 0xff) == 0){
                                    if((input[y-1][x] & 0xff) == 255 || (input[y][x-1] & 0xff) == 255) {
                                        output[x][y] = 255;
                                        b=true;
                        for(y=ye-2;y>=1;y--) {
                            for(x=xe-2;x>=1;x--) {
                                if ((input[y][x]& 0xff)==0){
                                    if((input[y][x+1]& 0xff)==255 || (input[y+1][x]& 0xff)==255) {
                                        output[x][y] = 255;
                                        b=true;
                    }Any idea why?

    There are a number of issues with the code:
    1. The pixels array is never used after its initial creation.
    2. Your output isn't a direct copy of your input - values are reflected about a line from 0,0 to xe-1, ye-1. Maybe you wanted this?
    3. Are you sure this test (input[y][0]& 0xff)==0) is correct? It's equivalent to the much clearer (input[y][0] == 0).
    4. The cause of your infinite loop is that the values in your tests never change. You test the values in the input but change the values in the output.
    Cheers.

  • Oracle Arrays and getVendorConnection API and Class Cast Exception

    I 've gone through various threads relating to the topic of Oracle Arrays and the getVendorConnecton API call to avoid the class Cast Exception.. i ve used all these but am still facing the problem...
    I would appreciate it if some one could resolve the following queries :
    I am using Weblogic 8.1 SP5 with oracle 8i
    1. I read that the need to use the getVendorConnection API to make pl/sql proc calls with oracle arrays from the WL Server wont be required to avoid classCastException...
    I tried to use the connection from the WL connection pool ..but it didnot work....I used the getVendorConnection API ..which also doesnot seem to work..
    I got the Heurisitc Hazard exception...I used the Oracle 9i driver ie ojdbc14.jar ...after this the exception is not coming but still the code doesnt seem to work...
    the snippet of the code is pasted below :
    ~~~~~~~~~~~~~~~~~~~~~~~code is : ~~~~~~~~~~~~~~~~~~~
    /*below :
    logicalCon is the Connection from the WL connection pool
    JDBCcon is the JDBC connection. */
    <div> try </div>
    <div>{ </div>
    <div>
    <b>vendorConn</b> = ((WLConnection)logicalCon).getVendorConnection();
    </div>
    <div>
    //Calling the procedure
    </div>
    <div>
    //java.util.Map childMap1 = JDBCcon.getTypeMap();
    </div>
    <div>
    java.util.Map childMap1 = <b>vendorConn</b>.getTypeMap();
    </div>
    <div>
    childMap1.put("SST_ROUTE_ENTRY", Class.forName("svm.stport.ejb.StaticRouteEntry"));
    </div>
    <div>
    //JDBCcon.setTypeMap(childMap1);
    <b>vendorConn</b>.setTypeMap(childMap1);
    </div>
    <div>
    // Create an oracle.sql.ARRAY object to hold the values
    </div>
    <div>
    /*oracle.sql.ArrayDescriptor arrayDesc1 = oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", JDBCcon); */
    </div>
    <div>
    oracle.sql.ArrayDescriptor arrayDesc1 =
    oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", <b>vendorConn</b>); // here if i use the JDBCcon it works perfectly.... <u>^%^%^%</u>
    </div>
    <div>
    code to fill in the sst route entry array....
    .....arrayValues1 */
    </div>
    <div>
    /* oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, JDBCcon, arrayValues1); */
    </div>
    <div>
    oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, <b>vendorConn</b>, arrayValues1);
    </div>
    <div>
    callStatement = logicalCon.prepareCall( "? = call procName(?, ?, ?)");
    </div>
    <div>
    /* ..code to set the ?s ie array1 */
    </div>
    <div>
    callStatement.execute();
    </div>
    <div>
    }catch(Exceptio e){
    </div>
    <div>
    }</div>
    <div>
    finally </div>
    </div>{</div>
    <div>System.out.println(" I ve come to finally"); </div>
    <div>}</div>
    <div>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~code snippet ends here ~~~~~~~~~~~~~~``
    </div>
    I have observed that the control immediately comes to the finally block after the call to the createDescriptor line above with <u>^%^%^%</u> in the comment. If i use the JDBCCon in this line...it works perfectly fine.
    Any pointers to where anything is getting wrong.
    I have jst set the vendorCon to null in the end of the file and not closed it. Subsequently i have closed the logicalCon. This has been mentioned in some of the thread in this forum also.
    Thanks,
    -jw

    Jatinder Wadhwa wrote:
    I 've gone through various threads relating to the topic of Oracle Arrays and the getVendorConnecton API call to avoid the class Cast Exception.. i ve used all these but am still facing the problem...
    I would appreciate it if some one could resolve the following queries :
    I am using Weblogic 8.1 SP5 with oracle 8i
    1. I read that the need to use the getVendorConnection API to make pl/sql proc calls with oracle arrays from the WL Server wont be required to avoid classCastException...
    I tried to use the connection from the WL connection pool ..but it didnot work....I used the getVendorConnection API ..which also doesnot seem to work..
    I got the Heurisitc Hazard exception...I used the Oracle 9i driver ie ojdbc14.jar ...after this the exception is not coming but still the code doesnt seem to work...
    the snippet of the code is pasted below :
    ~~~~~~~~~~~~~~~~~~~~~~~code is : ~~~~~~~~~~~~~~~~~~~Hi. Show me the whole exception and stacktrace if you do:
    try
    vendorConn = ((WLConnection)logicalCon).getVendorConnection();
    java.util.Map childMap1 = vendorConn.getTypeMap();
    childMap1.put("SST_ROUTE_ENTRY" Class.forName("svm.stport.ejb.StaticRouteEntry"));
    vendorConn.setTypeMap(childMap1);
    oracle.sql.ArrayDescriptor arrayDesc1 =
    oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR",
    vendorConn);
    oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, vendorConn, arrayValues1);
    callStatement = logicalCon.prepareCall( "? = call procName(? ? ?)");
    callStatement.execute();
    }catch(Exception e){
    e.printStackTrace();
    finally
    try{logicalCon.close();}catch(Exception ignore){}
    System.out.println(" I ve come to finally");
    /*below :
    logicalCon is the Connection from the WL connection pool
    JDBCcon is the JDBC connection. */
    <div> try </div>
    <div>{ </div>
    <div>
    <b>vendorConn</b> = ((WLConnection)logicalCon).getVendorConnection();
    </div>
    <div>
    //Calling the procedure
    </div>
    <div>
    //java.util.Map childMap1 = JDBCcon.getTypeMap();
    </div>
    <div>
    java.util.Map childMap1 = <b>vendorConn</b>.getTypeMap();
    </div>
    <div>
    childMap1.put("SST_ROUTE_ENTRY", Class.forName("svm.stport.ejb.StaticRouteEntry"));
    </div>
    <div>
    //JDBCcon.setTypeMap(childMap1);
    <b>vendorConn</b>.setTypeMap(childMap1);
    </div>
    <div>
    // Create an oracle.sql.ARRAY object to hold the values
    </div>
    <div>
    /*oracle.sql.ArrayDescriptor arrayDesc1 = oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", JDBCcon); */
    </div>
    <div>
    oracle.sql.ArrayDescriptor arrayDesc1 =
    oracle.sql.ArrayDescriptor.createDescriptor("SST_ROUTE_ENTRY_ARR", <b>vendorConn</b>); // here if i use the JDBCcon it works perfectly.... <u>^%^%^%</u>
    </div>
    <div>
    code to fill in the sst route entry array....
    .....arrayValues1 */
    </div>
    <div>
    /* oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, JDBCcon, arrayValues1); */
    </div>
    <div>
    oracle.sql.ARRAY array1 = new oracle.sql.ARRAY(arrayDesc1, <b>vendorConn</b>, arrayValues1);
    </div>
    <div>
    callStatement = logicalCon.prepareCall( "? = call procName(?, ?, ?)");
    </div>
    <div>
    /* ..code to set the ?s ie array1 */
    </div>
    <div>
    callStatement.execute();
    </div>
    <div>
    }catch(Exceptio e){
    </div>
    <div>
    }</div>
    <div>
    finally </div>
    </div>{</div>
    <div>System.out.println(" I ve come to finally"); </div>
    <div>}</div>
    <div>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~code snippet ends here ~~~~~~~~~~~~~~``
    </div>
    I have observed that the control immediately comes to the finally block after the call to the createDescriptor line above with <u>^%^%^%</u> in the comment. If i use the JDBCCon in this line...it works perfectly fine.
    Any pointers to where anything is getting wrong.
    I have jst set the vendorCon to null in the end of the file and not closed it. Subsequently i have closed the logicalCon. This has been mentioned in some of the thread in this forum also.
    Thanks,
    -jw

  • How can I make a BufferedImage out of packed and non-packed int pixels?

    Hi all,
    I'm trying to turn a byte array of pixels into an int array, then into a buffered Image. In addition to the pixels, I've also got the color (and alpha) masks, width, height, and bit depth of the image. My problem is that the bits per pixel can change, the individual bytes cannot contain the pixels, and many times an int is not fully utilized to store an entire pixel (16bit pixels, for example). When I attempt to create a WritableRaster with a DataBufferInt, I get errors that I don't get if I re-package the 16bit pixels in a short[], (using DataBufferUShort). I don't want to have to do this, since it means reprocessing the entire array yet another time. One last thing. I've already got a working method for "up-converting" the int[] to 32bit pixels, though I'd love to see somebody else's attempt at this if they'd like to share. Mostly, I'm just looking for a way to use the data I have to create a BufferedImage that preserves the data type of the data. Here's some of the code I'm using now. (The byte array may contain MIPmaps, so that's the reason for the imgIndex...)
    <edit> Sorry, I also don't want to have to use the switch (or if...else) statements. I'm looking for a way to use the info I have to write one piece of code that will work for all the data types...</edit>
    private static int[] get8888(byte[] pixels, int format, int width, int height, int imgIndex) {
       int[] pixels8888 = new int[width * height / (int)Math.pow(4, imgIndex)];
       int offset = 0;
       for(int i = 0; i < imgIndex; i++) {
          offset += (width * height) / (int)Math.pow(4, i);
       switch(format) {
          case TYPE_A8R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 4] & 0xff) | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | (pixels[(i + offset) * 4 + 3] & 0xff) << 24;
             break;
          case TYPE_A1R5G5B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] & 0xff | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = ( ( (pixels8888[i] & 0x8000) >>> 15 ) == 1 ) ? 0xFF : 0;
                int r = (pixels8888[i] & 0x7c00) >>> 7;
                int g = (pixels8888[i] & 0x3e0) >>> 2;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_A4R4G4B4:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int a = (pixels8888[i] & 0xf000) >>> 12;
                int r = (pixels8888[i] & 0xf00) >>> 8;
                int g = (pixels8888[i] & 0xf0) >>> 4;
                int b = (pixels8888[i] & 0xf);
                a = a | (a << 4);
                r = r | (r << 4);
                g = g | (g << 4);
                b = b | (b << 4);
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_A8R3G3B2:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int a = (pixels8888[i] & 0xff00) >>> 8;
                int r = (pixels8888[i] & 0xe0);
                int g = (pixels8888[i] & 0x1c) << 3;
                int b = (pixels8888[i] & 0x3) << 6;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 3] & 0xff) | (pixels[(i + offset) * 3 + 1] & 0xff) << 8 | (pixels[(i + offset) * 3 + 2] & 0xff) << 16 | 0xff000000;
             break;
          case TYPE_R5G6B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = 0xFF;
                int r = (pixels8888[i] & 0xf800) >>> 8;
                int g = (pixels8888[i] & 0x7e0) >>> 3;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_R3G3B2:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset)];
                int a = 0xFF;
                int r = (pixels8888[i] & 0xe0);
                int g = (pixels8888[i] & 0x1c) << 3;
                int b = (pixels8888[i] & 0x3) << 6;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_X8R8G8B8:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 4]) & 0xff | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | 0xff000000;
             break;
          case TYPE_X1R5G5B5:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
                int a = 0xff;
                int r = (pixels8888[i] & 0x7c00) >>> 7;
                int g = (pixels8888[i] & 0x3e0) >>> 2;
                int b = (pixels8888[i] & 0x1f) << 3;
                pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
             break;
          case TYPE_X4R4G4B4:
             for(int i = 0; i < pixels8888.length; i++) {
                pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
                int r = (pixels8888[i] & 0xf00) >>> 8;
                int g = (pixels8888[i] & 0xf0) >>> 4;
                int b = (pixels8888[i] & 0xf);
                r = r | (r << 4);
                g = g | (g << 4);
                b = b | (b << 4);
                pixels8888[i] = 0xff << 24 | r << 16 | g << 8 | b;  
             break;
          default:
             System.out.println("File type not recognized");
       return pixels8888;
    }After I've done this, I can just create a DataBufferInt with the returned pixel array and generate the bufferedImage. I'm doing this currently, but I'd like to be able to write code that would take the image type and return a matching BufferedImage, (of type TYPE_USHORT_565 for example). Any hints?
    Edited by: Quasi_Stomach on Jul 31, 2009 12:33 PM

    i figured it out myself !!!

  • Quick question how to wrie entire array in one go without loop

    I have the following loop, which goes around store array and write each element to file one at a time, i have been told that i can do this an easy way by writting the entire array at once. Can anybody tell me how to do this?
    int storeSize = store.getCount();
    for (int i = 0; i<storeSize;i++)
    output.writeObject(store.elementAt(i));

    i believe the method is
    Arrays.fill(
    read the api of the Arrays classPerhaps you should read the API, too, before
    offering advice.eerm, i dont need to read the api because i know this method exists:
    static void      fill(Object[] a, Object val)
    Assigns the specified Object reference to
    each element of the specified array of Objects.I'm sorry, you're absolutely right. Original poster, stop serializing objects
    to that ObjectOutputStream, and instead fill an array with multiple
    references to the same value. Whew, that was a close one, eh mates?

  • Place contents of xml file to 2D array

    i have a xml file like
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE map SYSTEM "map.dtd">
    <map width="5" height="5" goal="6" name="Hallways of Dooom">
         <random-item type='lantern' amount='5' />
         <random-item type='health' amount='10' />
         <tile x="1" y="0" type="floor">
              <renderhint>floor:wood</renderhint>
         </tile>
         <tile x="0" y="1" type="wall" />
         <tile x="1" y="1" type="floor" startlocation="1" />
         <tile x="3" y="1" type="floor">
              <item type="treasure">Bar of Silver</item>
              <renderhint>floor:stone,blood</renderhint>
         </tile>
    </map>i was asked to creat a 5*5 2D array from it. each tile represents a position on the point. If the type of tile is wall, it is represented by number 2; if it is floor, it is represented by number 1.
    i have written my code as following:
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import java.io.*;
    public class parsexml
        public void parseXML()
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setValidating(true);
         factory.setIgnoringElementContentWhitespace(true);
         try {
             DocumentBuilder parser = factory.newDocumentBuilder();
             Document doc = parser.parse(new File("hallways.xml"));
             System.out.println("XML file parsed.");
             processTree(doc);
         } catch (ParserConfigurationException e) {
             e.printStackTrace();
         } catch (SAXException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
        public void processTree(Document doc)
         int column = 0;
         int row = 0;
         int hori = 0;
         int vert = 0;
         String Type = "";
         Node element = doc.getDocumentElement();
         NamedNodeMap attrs = element.getAttributes();
         for (int i = 0; i < attrs.getLength(); i++) {
             Node attr = attrs.item(i);
             String attrName = attr.getNodeName();
             if (attrName == "width") {
              column = Integer.parseInt(attr.getNodeValue());
             if (attrName == "height") {
              row = Integer.parseInt(attr.getNodeValue());
         int[][] map = new int[row][column];
         NodeList children = element.getChildNodes();
         for (int i = 0; i < children.getLength(); i++) {
             Node child = children.item(i);
             String nodeName = child.getNodeName();
             if (nodeName == "tile") {
              NamedNodeMap attributes = child.getAttributes();
              for (int a = 0; a < attributes.getLength(); a++) {
                  Node attribute = attributes.item(a);
                  String attributeName = attribute.getNodeName();
                  if (attributeName == "x") {
                   hori = Integer.parseInt(attribute.getNodeValue());
                  if (attributeName == "y") {
                   vert = Integer.parseInt(attribute.getNodeValue());
                  if (attributeName == "type") {
                   Type = attribute.getNodeValue();
             if (Type == "floor") {
              map[hori][vert] = 1;
             } else if (Type == "wall") {
              map[hori][vert] = 2;
         print(map);
        public void print(int[][] map)
         for (int r = 0; r < map.length; r++) {
             for (int c = 0; c < map[r].length; c++) {
              System.out.print(map[r][c]);
             System.out.println();
        public static void main(String[] args)
         parsexml xml = new parsexml();
         xml.parseXML();
    }When i run the program, i found it doesn't fills the spcified position on the array. all I get is a 5*5 grid of 0s.
    Can anyone tells me why? thank you in advance.

    Unless someone is willing to put in the time to do your job for you, you'll have to debug it yourself. Put in some debugging statements. In their simplest form this is just a bunch of System.out.println("your message here") calls where you put in messages describing the current point of execution (like what method you just started or are about to finish) and the values of relevant data (such as method parameters, loop indices, whatever you feel is important).
    Then run the program and see what it tells you.

  • I have read 118 files (from a directory) each with 2088 data and put them into a 2 D array with 2cols and 246384row, I want to have aeach file on a separate columns with 2088 rows

    I have read 118 files from a directory using the list.vi. Each file has 2 cols with 2088rows. Now I have the data in a 2 D array with 2cols and 246384rows (118files * 2088rows). However I want to put each file in the same array but each file in separate columns. then I would have 236 columns (2cols for each of the 118 files) by 2088 rows. thank you very much in advance.

    Hiya,
    here's a couple of .vi's that might help out. I've taken a minimum manipulation approach by using replace array subset, and I'm not bothering to strip out the 1D array before inserting it. Instead I flip the array of filenames, and from this fill in the end 2-D array from the right, overwriting the column that will eventually become the "X" data values (same for each file) and appear on the right.
    The second .vi is a sub.vi I posted elsewhere on the discussion group to get the number of lines in a file. If you're sure that you know the number of data points is always going to be 2088, then replace this sub vi with a constant to speed up the program. (by about 2 seconds!)
    I've also updated the .vi to work as a sub.vi if you wa
    nt it to, complete with error handling.
    Hope this helps.
    S.
    // it takes almost no time to rate an answer
    Attachments:
    read_files_updated.vi ‏81 KB
    Num_Lines_in_File.vi ‏62 KB

Maybe you are looking for

  • 3D option not working in Photoshop CS6

    I have Toshiba computer, Vista and I can't get 3D to work. I looks like Adobe Creative Cloud might not be compatible. I need 3D to work for my class at college. It keeps telling me OpenGL us disabled. I can't find a solution to enable it. Anyone have

  • To render or not to

    Do I need to " render " my edited video? and if so do I render before I add sound track and also before I save it or save it then " render" Thanks for your help Joe Geoffroy

  • JDBC or Entity Beans for Read-Only Data?

    Entity beans are way to slow on pulling the amount of data I need. What are the cons of just using JDBC? Is this bad programming? One query pulls about 700 rows from 6 different tables taking up to 20 seconds. The same call using JDBC takes 2 seconds

  • Editting Manager's desktop

    Dear Gurus, i need to edit and remove unnecessary colums eg object types, relationsship, relationship texts etc anyone, please advise on how to go about it.

  • BLACKBERRY APP WORLD DISAPPEARED!! :O

    Hellooo, I have done absolutley nothing to my blackberry 9320 and some how my Blackberry App World has disappeared, I have done no update but its gone ! HELPPPPP keaton