Pixelgrabber problem

Hi,
I have a problem with an applet which loads an image from url. First I load the image (png) and second I try to grab it (with pixelgrabber) in order to extract a pixel array (integer array) . But there is a problem and the pixel array is empty (note : If I use a java pluggin I works fine but IE VM doesn't work fine with png image)
I wonder if it were possible to transform a byte array (that I use to create my image) directly to a pixel array without create the image
Any idea ?

If I remember correctly you need to go back to java 1 version 1.1.8 (or how ever they did the numbeing back then) pre-java 2 for compliance with MS's product. MS did their normal thing and changed the language to suite thier model better, which in and of itself sounds like a decent enough idea, but the effect is--if you develop with MS's product, then everyone else is broken. If you develop with Sun's product and use any of the newer features--then MS is broken.
You just have a bit of code which is not supported in the MS VM, try to find the old standard from Java 1 and stick with it.

Similar Messages

  • PixelGrabber is too slow and has memory problems!

    Have any of you figured out a way to get pixels from an Image
    WITHOUT using PixelGrabber??
    PixelGrabber is really slow -- is a memory hog -- and has other problems
    that cause me to need another way to get pixels from an image.
    Does anyone else have a way to get the pixels directly from an Image
    without using PixelGrabber?
    Ken Warner

    Hi, there are ways to do it if you can live with certain restrictions.
                BufferedImage img=new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB);
                img.setRGB(10,15,0x01020304);   // a=1 r=2 g=3 b=4
                WritableRaster r=img.getRaster();
                DataBuffer db=r.getDataBuffer();
                if (db.getDataType() != DataBuffer.TYPE_INT)
                    throw new IllegalStateException("Hey that must be a int!");
                if (db.getNumBanks() != 1)
                    throw new IllegalStateException("Uh - Someone else got to do this job!");
                DataBufferInt dbi=(DataBufferInt)db;
                int[] data=dbi.getData();           
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));
                // Test: No coy
                data[10+32*15]=0xaabbccdd;
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));As you see it works best if you can set the pixel format and if it only contains a single array of data (i.e. bank).

  • Problem with ImageProducer/PixelGrabber

    I'm having a problem using PixelGrabber in my applet, that seems to be related to caching. I load an image through plain old Applet.getImage(), track that it's loaded via MediaTracker, then use PixelGrabber to grab the image into an integer array, all using your basic textbook code. What I find in testing is that even after the image is loaded (apparently either from a cache or from a URL) the PixelGrabber operation loads the image across the network all over again(!) every time, which I can see by watching debugging output and watching network activity, apparently ignoring the image data already obtained, which essentially doubles the image load time (a problem on modems) when using PixelGrabber. I'm wondering if this is a bug in the ImageProducer object, or if there's something about the implementation of PixelGrabber that specifically prevents using existing image data. I'm testing with IE, JVM version 5.0.0.3805, which is the target platform. Any help would be greatly appreciated!
    -Bob

    That's because your ImageProducer is still the original image. Just because you've snagged the pixels doesn't mean you've changed the source of the image. Once you have the data in an array create a new MemoryImageSource. Make a new image using that as a source. Note that the createImage method shown in the API is from java.awt.Component.

  • Problem using PixelGrabber ( cannot resolve symbol ) - newbie

    Hi All,
    I have a problem with my short program because the compiler write this (jdk1.4) :
    img.java:17: cannot resolve symbol
    symbol : constructor PixelGrabber (java.awt.Image,int,int,int,int,int[],int)
    location: class java.awt.image.PixelGrabber
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this
    ),image.getHeight(this),pixels,0);
    ^
    1 error
    ... And I wrote that in my code :
    ( all is OK, the bug is only when I uncomment the line where the PixelGrabber object
    is needed in my program ).
    Thanks if you have any idea of solution to solve this problem or a doc,
    ( I don't find the answer to my problem in http://java.sun.com/j2se/1.4/docs/api/java/awt/image/PixelGrabber.html ),
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.awt.image.PixelGrabber;
    public class img extends Applet {
    Image image;
    int pixels[];
    public void init() {
    image = getImage(getDocumentBase(), "rouge.jpg");
    pixels = new int[image.getWidth(this) * image.getHeight(this)];
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0);
         pg.grabPixels();
    public void paint(Graphics g) {
              String s = Integer.toString(pixels[5], 16);
              g.drawString(s, 50, 50);

    Hi,
    PixelGrabber needs one more parameter scansize (width).
    change this line;
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0);
    to:
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0, image.getWidth(this)
    );

  • Problem with save_image_look...

    why in program image alpha filter when save image is good in my program but when i look in windows xp image is no good_look why? code     public static boolean hasAlpha(Image image) {
            // If buffered image, the color model is readily available
            if (image instanceof BufferedImage) {
                BufferedImage bimage = (BufferedImage)image;
                return bimage.getColorModel().hasAlpha();
            // Use a pixel grabber to retrieve the image's color model;
            // grabbing a single pixel is usually sufficient
          //  PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
           PixelGrabber pg = new PixelGrabber(image,100,100,100,100,true);
            try {
                pg.grabPixels();
            } catch (InterruptedException e) {
            // Get the image's color model
            ColorModel cm = pg.getColorModel();
            return cm.hasAlpha();
        public static BufferedImage toBufferedImage(Image image) {
            if (image instanceof BufferedImage) {
                return (BufferedImage)image;
            // This code ensures that all the pixels in the image are loaded
            image = new ImageIcon(image).getImage();
            // Determine if the image has transparent pixels; for this method's
            // implementation, see e661 Determining If an Image Has Transparent Pixels
        //   boolean hasAlpha = hasAlpha(image);
            // Create a buffered image with a format that's compatible with the screen
            BufferedImage bimage = null;
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            try {
                // Determine the type of transparency of the new buffered image
                int transparency = Transparency.TRANSLUCENT;
            //    if (hasAlpha) {
            //        transparency = Transparency.BITMASK;
                // Create the buffered image
                GraphicsDevice gs = ge.getDefaultScreenDevice();
                GraphicsConfiguration gc = gs.getDefaultConfiguration();
                bimage = gc.createCompatibleImage(
                    image.getWidth(null), image.getHeight(null),transparency);
            } catch (HeadlessException e) {
                // The system does not have a screen
            if (bimage == null) {
                // Create a buffered image using the default color model
                int type = BufferedImage.TYPE_4BYTE_ABGR_PRE;
           //     if (hasAlpha) {
           //         type = BufferedImage.TYPE_INT_ARGB;
                bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),type);
            // Copy image to buffered image
            Graphics g = bimage.createGraphics();
            // Paint the image onto the buffered image
            g.drawImage(image, 0, 0, null);
            g.dispose();
            return bimage;
        private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
        alert();
        if(flaga_button==true){
                try {
                    System.out.print("test");
                    BufferedImage input = toBufferedImage(dst);
                    // Create the buffered image
                    //(BufferedImage) dst;
                    File outputFile = file;
                    if (outputFile == null) {
                        System.err.println("prosze wybrać obrazek");
                    } else {
                        ImageIO.write(input, "JPG", outputFile);
                } catch (IOException ex) {
                    Logger.getLogger(ImageViewView.class.getName()).log(Level.SEVERE, null, ex);
        } please make for good code...

    thanks Peter for trying to help
    ok, i've narrowed down the problem, it seems that when i try and save a file onto one partition of one of my ext drives it won't save to my last save dir but if i save to another partition/drive it works ok, also if i rename the 'dodgy' partition it also seems to work ok, so somehow the name of the drive has become corrupted.
    anybody ever heard of this? or how i could fix this as it's a quite annoying because alot of my audio files are referenced on this partition, so itunes or Cubase (audio sequencer) can't find my files now.

  • PB: PixelGrabber, offscreen Image, Windows 98, ie5

    Hello,
    I've got a problem with a bug that occurs under Windows 98, and ie5.
    This is the code of a little applet that works fine under Windows NT, but not under Windows 98:
    This applet draws 3 colors in a square, and use the grabPixel method for catching the pixels of the image and create another image with those pixels.(the image should be the same)
    The problem is that the grabPixel method changes the colors of the pixels. It occurs only with an offscreen Image (that means an Image created with the createImage(w, h) method). there is no problem with a MemoryImageSource, for example.
    I just notice that the ColorModel of an offscreen Image is not the same as the default ColorModel:
    colorModel: java.awt.image.DirectColorModel = {...}
    red_mask: int = 0xf800 (instead of 0x00ff0000 )
    green_mask: int = 0x7e0 (instead of 0x0000ff00 )
    blue_mask: int = 0x1f (instead of 0x000000ff)
    alpha_mask: int = 0x0 (instead of 0xff000000)
    red_offset: int = 0xb
    green_offset: int = 0x5
    blue_offset: int = 0x0
    alpha_offset: int = 0x0
    red_scale: int = 0x1f
    green_scale: int = 0x3f
    blue_scale: int = 0x1f
    alpha_scale: int = 0x0
    But i don't know how to solve the bug.
    Here is the code :
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    public class AppletFlush extends Applet implements Runnable{
    Thread anim;
    Image memimg;
    boolean bool;
    Image offImage;
    Graphics offGraphics;
         public void init() {
         public void start() {
         anim = new Thread(this);
         anim.start();
    bool = true;
    offImage = this.createImage(100, 100);
    offGraphics = offImage.getGraphics();
         public synchronized void stop() {
         anim = null;
         notify();
         public synchronized void run() {
         while (Thread.currentThread() == anim) {
    int[] pixels = new int[100 * 100];
    int color = 0;
    //set the pixels of a squared image that contains 3 colors (this is my reference image)
    if (bool)
    bool = false;
    for (int i=0; i<100; i++)
    if (i<33)
    color = 0xffff0000;
    else if (i<66)
    color = 0xff00ff00;
    else
    color = 0xff0000ff;
    for (int j=0; j<100; j++)
    pixels[i*100 + j] = color;
    else
    //grab the pixels of the offscreen image(here is the problem)
    PixelGrabber pg = new PixelGrabber(offImage, 0, 0, 100, 100, pixels, 0, 100);
    try
    pg.grabPixels();
    catch (InterruptedException ex)
    System.out.println("erreur pendant gragPixels !!!");
    //create the new image with the pixels
    MemoryImageSource imgsrc = new MemoryImageSource(100, 100, pixels, 0, 100);
    memimg = createImage(imgsrc);
    //draw the image in the offscreen image
    offGraphics.drawImage(memimg, 0, 0, null);
              repaint();
              try {wait(1000);} catch (InterruptedException e) {return;}
         public void paint(Graphics g) {
         // display the offscreen image
         g.drawImage(offImage, 0, 0, this);
    PLEASE HELP !
    YaYa

    try
    public void paint(Graphics g )
    if((_offScreen != null)&&(offScreenImage != null))
    // put your stuff here
    else
    update(g);
    g.dispose();
    g.finalize();
    return;
    public void update(Graphics g)
    if( offScreenImage == null)
    offScreenImage = this.createImage( width, height );
    if( _offScreen == null)
    _offScreen = offScreenImage .getGraphics();
    paint(g);
    }

  • Problem with Transparency using PixelGrabbar.

    Well, im having a problem.
    Im creating a basic 2d game and using images, since im using alot of images and they are being drawn alot i use a class i call "GameSprite", basically it retrieves the file needed and then keeps it in a pixel array, but transparency dosn't seem to work with it. The reason im using this is because say i have 100 images to draw, it dosn't need to keep using the drawImage method because it draws all at once using a set drawing area on which the pixel arrays are possitioned, for example this is the drawing;
    public void drawGraphics(int xOffset, Graphics g, int yOffset)
            setImageConsumer();
            g.drawImage(drawingAreaImage, xOffset, yOffset, this);
    .private synchronized void setImageConsumer()
            if(imageConsumer != null)
                imageConsumer.setPixels(0, 0, drawingAreaHeight, drawingAreaWidth, colorModel, drawingAreaSize, 0, drawingAreaHeight);
                imageConsumer.imageComplete(2);
        }Here is the basic's of what it does, note i used URL just for a test if you wanted to test (image still is uploaded there);
    Image image = Toolkit.getDefaultToolkit().createImage(new URL("http://i166.photobucket.com/albums/u116/the_owner2007/testtrans.png"));
              image = setTransparency(image, new Color(255, 89, 255));
              ImageIcon icon = new ImageIcon(image);
              imageWidth = icon.getIconWidth();
              imageHeight = icon.getIconHeight();
              imagePixels = new int[imageWidth * imageHeight];
              PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, imageWidth, imageHeight, imagePixels, 0, imageWidth);
                 pixelgrabber.grabPixels();If i use for example a JLabel and set an ImageIcon as the image the transparency works, otherwise i can't figure it out.
    Here is the setTransparency method;
    public static Image setTransparency(Image im, Color color) {
            //the color to make transparent
            final int markerRGB = color.getRGB() & 0x00FFFFFF;
            ImageFilter filter = new RGBImageFilter() {
                public int filterRGB(int x, int y, int rgb) {
                    if ((rgb & 0x00FFFFFF) == markerRGB) {
                        return markerRGB;
                    } else {
                        return rgb;
            ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
            return java.awt.Toolkit.getDefaultToolkit().createImage(ip);
    If you can think of an alternative solution which would work better and possibly more efficiant please feel free to post that.
    Thanks.

    drawingAreaImage = component.createImage(this);Note that images created through this method are often times immutable. They will not respond to changes in the underlying ImageProducer. So "drawingAreaImage" is essentially a snapshot of whatever pixels "this" gave it.
    An exception to this rule is if you use MemoryImageSource and set the animated flag,
    int[] pixels = ....
    MemoryImageSource imageProducer = ....
    imageProducer.setAnimated(true);
    drawingAreaImage = component.createImage(imageProducer);This time, whenever pixels is modified you can call imageProducer.newPixels() and the image will be updated.
    On a side note, you are using a very old method of dealing with images (over a decade old since java 1.0 and 1.1). Are you doing this for compatability purposes? I would recommend you drop the ImageProducer/Consumer model entirely and stick with BufferedImages (which as been around since 1.2 and was the "upgrade" from the ImageProducer/Consumer model).

  • Problem with dimension of an image loaded from a database

    Hi,
    I succeed in saving image in a MSAccess database with this code:
    Image img;
    image = new ImageIcon("d:\\prova\\comore.jpg");
    img=image.getImage();
    try{
    int[] pix = new int[img.getWidth(null) * img.getHeight(null)];
    PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(this), img.getHeight(this), pix, 0, img.getWidth(this));
    pg.grabPixels();
    System.out.println(pix.length);
    byte[] pixels = new byte[img.getWidth(this) * img.getHeight(this)*4];
    for(int j=0;j<pix.length;j++){
    pixels[j] = new Integer(pix[j]).byteValue();
    String sql="insert into Immagini values ('1',?)";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setBytes(1,pix);
    ps.executeUpdate();
    }catch(Exception except){
    except.printStackTrace();
    then, I've load the image with this code:
    try{
    String query = "select * from Immagini where IDprog = 1";
    Statement s = con.createStatement();
    s.executeQuery(sql);
    ResultSet rs=s.getResultSet();
    rs.next();
    Viaggio vi = new Viaggio(rs.getInt(1),rs.getBytes(2));
    byte[] b=vi.getBytesImage();
    int[] intImage = new int[b.length];
    for(int j=0;j<b.length;j++){
    intImage[j]=(int)b[j];
    Image img = createImage(new MemoryImageSource(124,100,intImage,0,124));
    ImageIcon imgic = new ImageIcon(img);
    jLabel3.setIcon(imgic);
    }catch(Exception tps){
    tps.printStackTrace();
    All works correctly;
    but I've two problems:
    How do I do to take the dimension of the image from the byte array?
    infact in the code up written I've used 124 and 100 as image dimension;
    but I can have images of different dimension.
    The other problem is:
    Why in the image that is loaded are not the same number of colors of the image saved, but only a few, so that the image seems to be out of focus?
    Thank and excuse me for my english.
    I'm Italian.

    Noone can help me?
    Thank

  • PixelGrabber is intermittently slow

    Hi All,
    PixelGrabber has some perfomance problems and there is a bug related to it here (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4835595). However I am facing a bug where a offscreen image sometimes gets slow while I am running the PixelGrabber, this is the stack trace :
    at java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(DirectColorModel.java:305)
    at java.awt.image.DirectColorModel.getRed(DirectColorModel.java:353)
    at java.awt.image.DirectColorModel.getRGB(DirectColorModel.java:438)
    at java.awt.image.PixelGrabber.setPixels(PixelGrabber.java:595)
    at sun.awt.image.OffScreenImageSource.sendPixels(OffScreenImageSource.java:130)
    at sun.awt.image.OffScreenImageSource.produce(OffScreenImageSource.java:161)
    at sun.awt.image.OffScreenImageSource.addConsumer(OffScreenImageSource.java:37)
    - locked <0x185b41c8> (a sun.awt.image.OffScreenImageSource)
    at sun.awt.image.OffScreenImageSource.startProduction(OffScreenImageSource.java:51)
    at java.awt.image.PixelGrabber.grabPixels(PixelGrabber.java:242)
    - locked <0x185b4190> (a java.awt.image.PixelGrabber)
    at java.awt.image.PixelGrabber.grabPixels(PixelGrabber.java:209)
    Would somebody know if the intermittent slowness can be associated to the bug above ? ( in the bug it states it always happens) Has somebody ever had the same problem ?
    Thanking you in advance
    Ary Alves

    Hi, there are ways to do it if you can live with certain restrictions.
                BufferedImage img=new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB);
                img.setRGB(10,15,0x01020304);   // a=1 r=2 g=3 b=4
                WritableRaster r=img.getRaster();
                DataBuffer db=r.getDataBuffer();
                if (db.getDataType() != DataBuffer.TYPE_INT)
                    throw new IllegalStateException("Hey that must be a int!");
                if (db.getNumBanks() != 1)
                    throw new IllegalStateException("Uh - Someone else got to do this job!");
                DataBufferInt dbi=(DataBufferInt)db;
                int[] data=dbi.getData();           
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));
                // Test: No coy
                data[10+32*15]=0xaabbccdd;
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));As you see it works best if you can set the pixel format and if it only contains a single array of data (i.e. bank).

  • Call to PixelGrabber(???,

    I want to call the PixelGrabber(...) method, but I need help figuring out the correct value to send in for the first parameter.
    Basically I am loading an image "theSky.gif" into a Graphics2D object using the method drawImage(...)
    The Graphics2D object named "_2DSkyImage" will at various times during the program manipulate and change the copied image of "theSky.gif".
    Then I want to be able to send the modified image into the first parameter of the method PixelGrabber(...). The problem is that I do not know how to get a handle on the image referenced by the object _2DSkyImage, and then pass it into the first variable of PixelGrabber(...). Which I think would be of type ImageProducer (Not sure!)
    Anyway, here is the code. I hope the question is clear. I will award 4 points for this question and would appreciate help from someone who feels they can truly help me out. Thanks in advance,
    Amy Danough,
    the code is below:
    Image imgSKY_IMAGE;
    imgSKY_IMAGE=getImage(getDocumentBase(),"theSky.gif");
    private Graphics2D _2DSkyImage;
    private BufferedImage biSkyBuffer;
    biSkyBuffer = new
    BufferedImage(imgSkyImage.getWidth(this),
    imgSkyImage.getHeight(this),
    BufferedImage.TYPE_INT_ARGB);
    _2DSkyImage = biSkyBuffer.createGraphics();
    _2DSkyImage.drawImage(imgSKY_IMAGE,0,0,this);
    // ?????? represents the image referenced by _2DSkyImage but I don't
    // know how to get to the image which is referenced by _2DSkyImage.
    PixelGrabber pg;
    pg = new PixelGrabber(??????,0,0,width,height,image_array,0,width);

    At the moment, I don't really feel like writing the code verbatim to illustrate for you what I am attempting to explain. I think the confusion stems from a lack of understanding as to how the object references in your code interoperate. I will attempt to explain, and maybe code later if I feel up to it or if someone doesn't beat me to the punch. :) (It's Saturday, and I don't really want to spend it indoors coding....)
    Your Graphics2D object _2DSkyImage is a reference to the Graphics2D object that is generated by the BufferedImage biSkyBuffer. Thus, when call any of the drawXXX() methods of your Graphics2D reference, it is drawing that information on to your image. If when you called the PixelGrabber constructor and gave it a reference to your BufferedImage, then, using the Graphics2D object drew something on your BufferedImage, it would (possibly) show up in the PixelGrabber. This is what we call a side-effect (though intended in this case). Once the image has been changed after you drew on it, you may have to tell the PixelGrabber object to reload the image data once it has been altered (via the Graphics2D object) so that it will track the changes.
    The worst case scenario is that you'd have to reinstantiate the PixelGrabber object every time you altered the image, and if that was the case, I would consider ditching the implementation. However, you shouldn't have to do this because PixelGrabber does have methods that allow you to reload pixel data without reinstantiating.
    Hopefully that clears it up. If not, let us know and we'll give it another shot. ;)
    -Dok

  • PixelGrabber.grabPixels() doesnt work

    I try to save my canvas object. It works always fine, but it seems that my personalJava (ARM) has a problem when my PixelGrabber calls grabPixels(). I tried it with milli-seconds, doesnt work.
    Then I deleted the grabPixels()-Method in my source and I get a black image.
    does anyone have the same problem or can help me to find perhaps an other solution?
    I tried it with pngEncoder from http://www.keypoint.com.

    Could you post your code so we can see what is going on?

  • PixelGrabber

    Hi all,
    I'm using the method grabPixel of the class PixelGrabber to get an array of pixels of an image.
    The problem is that the array I'm getting is not correct and the x right pixels(in my case 473 right pixels) in each line of the matrix of the image is shifted to the left part of that line and all of them get the value 0 (which is black).
    How can I avoid this problem?
    The following code is the code of the class using PixelGrabber:
    import javax.swing.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.awt.image.*;
    public class FilePanel extends JPanel {
    protected Image currentImage = null, modImg = null;
    private boolean isFile = false;
    private int pictureWidth, pictureHeight;
    private int count = 0;
    protected int[] pixels, pix;
    private MediaTracker tracker;
    private ColorModel colorModel;
    public FilePanel() {
    setBorder (BorderFactory.createTitledBorder("Picture Area:"));
    tracker = new MediaTracker(this);
    colorModel = ColorModel.getRGBdefault();
    public void setFile(String fileName)
    if (fileName != null)
    currentImage=null;
    isFile = true;
    if (fileName.endsWith(".bmp") || fileName.endsWith(".BMP"))
    BMP bmp = new BMP(new java.io.File(fileName));
    currentImage = bmp.getImage();
    else
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    currentImage = toolkit.getImage(fileName);
    try
    tracker.addImage(currentImage,11);
    tracker.waitForID(11);
    catch(InterruptedException e)
    e.printStackTrace();
    System.err.println("*ERROR* MediaTracker rudely interrupted.");
    currentImage=null;
    tracker.removeImage(currentImage);
    pictureWidth = currentImage.getWidth(this);
    pictureHeight = currentImage.getHeight(this);
    handlepixels(currentImage, (getWidth() - pictureWidth)/2 - 60, 0,
    pictureWidth, pictureHeight);
    isFile = true;
    repaint();
    public void paintComponent(Graphics g)
    if (currentImage != null && currentImage.getHeight(null)>=0)
    super.paintComponent(g);
    g.drawImage(currentImage, (this.getWidth() - 300)/2,
    (this.getHeight() - 90)/2, this);
    public byte[] sendPixel (byte byteArray[])
    int numOfBits = 8, numOfBytesInLine = pictureWidth/8,
    numOfLines = pictureHeight, countPixels = 0, gray,
    currentPixel, bit = -1;
    byte currentByte = 0;
    int j = 0;
    if (currentImage == null)
    System.out.println("Picture has not been loaded yet");
    return null;
    else
    for (int i = 0 ;i < pixels.length; i++)
    currentPixel = manipulatePixel(pixels);
    if (currentPixel > 128)
    currentByte &= 0xfe;
    else
    currentByte |= 0x01;
    bit++;
    if (bit != 7)
    currentByte <<= 1;
    else
    bit = -1;
    byteArray[i/8] = currentByte;
    currentByte = 0;
    return byteArray;
    public int manipulatePixel (int pixel)
    return ((pixel&0xff)+((pixel&0xff00)>>8)+((pixel&0xff0000)>>16))/3;
    public void handlepixels(Image img, int x, int y, int w, int h) {
    System.out.println("w "+w+" h "+h);
    pixels = new int[w * h];
    int red, green, blue;
         PixelGrabber pg = new PixelGrabber (img, x, y, w, h, pixels, 0, w);
         try {
         if (pg.grabPixels()&&((pg.getStatus() & ImageObserver.ALLBITS) != 0))
    else
    System.out.println("Did not succeed to grab pixles");
    catch (InterruptedException e) {
         System.err.println("interrupted waiting for pixels!");
         return;
    repaint();
    public int getNumOfLines () {return pictureHeight;}
    public int getNumOfBytesInLine () {return pictureWidth/8;}
    Thanks,
    gabi

    Method is somethig like this:
    public void handlepixels(Image img, int x, int y, int w, int h)
              int[] pixels = new int[w * h];
              �
              PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
              try
              pg.grabPixels();
              catch (InterruptedException e)
              for (int j = 0; j < h; j++)
    for (int i = 0; i < w; i++)
                   //what do I need to do inside this loop?
         // Ineed to check pixel by pixel if it is certain color and then convert it to
                   //different color.     
                   Image new_image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, image, 0, w));
         }

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

Maybe you are looking for

  • Autodiscovery not working at a complete loss

    Hi  I have a setup with one CAS server and one Exchange backend server. Serves 4 Domains. Activesynch is working (both on intranet and internet). owa is working both Networks too. heres some test data (domain and such stuff have been sanitized contos

  • Suggestion for not picking up the same record

    Hi All, I have a plsql procedure that picks up the records from the same table from multiple threads. Different threads should not pick up the same record. Current Logic: I am locking the row that has been picked up the current thread and the next th

  • How to use StreamTokenizer class ?

    i want to use StreamTokenizer class in my program so that when i read from a file i want to make tokens of words present in the file, but i dont know how to use this class in my program, as i didnt find any example which shows how to use StreamTokeni

  • Import iPhoto library into Bridge (in mac Elements )

    Hi, I am looking for a way to bring my iPhoto library into Elements 8 for Mac so that I can browse them in Bridge. The only way I saw to do that here in this forum is 'in PSE 8.0 File>Open. From the side panel of the "Open" window, select Photos unde

  • Query with two where conditions

    HI SELECT ENAME FROM EMP WHERE SAL > 1000 AND JOB='CLERK'; How to implement in CMP(Entity bean) thank u