Graphics.drawImage(Image, int, int, Observer) fails on custom CompositeMode

We created some custom CompositeModes for which the following trivial example code is representative:
import java.awt.*;
import java.awt.image.*;
public class AddARGBComposite implements Composite
     static private AddARGBComposite instance = new AddARGBComposite();
     final private float alpha;
     public static AddARGBComposite getInstance( final float alpha )
          if ( alpha == 1.0f ) { return instance; }
          return new AddARGBComposite( alpha );
     private AddARGBComposite()
          this.alpha = 1.0f;
     private AddARGBComposite( final float alpha )
          this.alpha = alpha;
     public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
          return new CompositeContext()
               public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
                    final int[] srcPixel = new int[ 4 ];
                    final int[] dstInPixel = new int[ 4 ];
                    for ( int x = 0; x < dstOut.getWidth(); x++ )
                         for ( int y = 0; y < dstOut.getHeight(); y++ )
                              src.getPixel( x, y, srcPixel );
                              dstIn.getPixel( x, y, dstInPixel );
                              final float srcAlpha = srcPixel[ 3 ] / 255.0f * alpha;
                              dstInPixel[ 0 ] = Math.min( 255, Math.round( srcPixel[ 0 ] * srcAlpha + dstInPixel[ 0 ] ) );
                              dstInPixel[ 1 ] = Math.min( 255, Math.round( srcPixel[ 1 ] * srcAlpha + dstInPixel[ 1 ] ) );
                              dstInPixel[ 2 ] = Math.min( 255, Math.round( srcPixel[ 2 ] * srcAlpha + dstInPixel[ 2 ] ) );
                              dstInPixel[ 3 ] = 255;
                              dstOut.setPixel( x, y, dstInPixel );
               public void dispose()
}Using this CompositeMode for composing two images using the trivial method fails :
BufferedImage image1, image2;
Graphics2D g = image1.getGraphics();
g.setComposite( AddARGBComposite.getInstance( 0.5f )  );
g.drawImage( image2, 0, 0, null );Using a trivial AfifneTransform, it also fails because for integer translation, Graphics seems to fall back to the integer method above:
AffineTransform at = new AffineTransform();
g.drawImage( image2, at, null );But for non-trivial AffineTransforms, it works perfectly:
at.scale( 0.5f, 0.5f );
g.drawImage( image2, at, null );We reproduced this on the Linux64 and Windows64 platform both with an Nvidia-graphics device and latest Sun Java 6 update 16.
Is the bug on our side missing something in the CompositeMode implementation or is this a bug in java.awt?
Thanks in advance for any helpful comments.

First, can you explain what you mean by fail - Is your compose method never called? Does it get called, but the results are unexpected? What are the results? Or is just as if image2 was never drawn?
Second, In you're test case, what types are image1 and image2?
BufferedImage image1, image2; //<-----
Graphics2D g = image1.getGraphics();
g.setComposite( AddARGBComposite.getInstance( 0.5f )  );
g.drawImage( image2, 0, 0, null );You're making two assumptions in your AddARGBComposite code: 1) The source image has an alpha channel and is un-premultiplied, and 2) both the source and destination images are in rgb space. This could conceivably cause certain combinations of image types to fail, which is why I ask what types your image1 and image2 are. All other things considered, it seems to work on my machine. Though I'm in a Windows32 environment with 1.6.0_16.
From experience though, there is a problem with creating a custom composite and using GUI widgets under the new D3D graphics pipeline that was made the default since java 1.6.10 (I think that's when it was made default, I can't remember).
Basically, one or all of src, dstIn, and dstOut use a DataBuffer of type D3DNativeDataBuffer. And traditional calls into this native DataBuffer to retrieve or set data elements end up creating a non-trivial object or two. Multiply that object creation by the many thousands of pixels in a single image and you have a noticiable slow down. It's a similar reason why drawing a BufferedImage.TYPE_CUSTOM is pretty slow.
Again, this only applies to throwing GUI widgets into mix, not drawing one user-created BufferedImage ontop of another.

Similar Messages

  • How to update drawImage() images

    This may be quite simple for most, but I'm stumped. I have BuffereredImages[] being passed to a class where my Graphics are. I then use drawImage() to draw the images on the JPanel. That all works fine. My problem is that I have a button that I need to repaint or redraw the images when the button is clicked. I have the button listener all setup. I just don't know how to get the drawImages() to redraw using different images.
    In my main panel I have:
             die1 = rand.nextInt(6);
             die2 = rand.nextInt(6) + 6;
             //get images for vending machine
                img = loadImages();
             //paint all images
                dieImg = new DiceImage(die1, die2, img);Then my button listener:
           private class ButtonListener implements ActionListener
             //declare variables 
             private Object source;
              public void actionPerformed(ActionEvent event)
                source = event.getSource();
                *   Roll Button         *
                if (source == rollBtn)
                  //paint all images
                *   Pass Button         *
                if (source == passBtn)
         System.out.println("Pass");
          } //end of Button Listener ClassThen this is where I get the images:
           private BufferedImage[] loadImages()
               //create prefix for path if needed
             String prefix = "";
               //create array of filenames to draw
             String[] fileNames = { "die1-1.gif", "die1-2.gif", "die1-3.gif", "die1-4.gif", "die1-5.gif", "die1-6.gif",
                                    "die2-1.gif", "die2-2.gif", "die2-3.gif", "die2-4.gif", "die2-5.gif", "die2-6.gif" };
             //get the files
             BufferedImage[] images = new BufferedImage[fileNames.length];
             for(int j = 0; j < images.length; j++)
                try
                   URL url = getClass().getResource(prefix + fileNames[j]);
                   images[j] = ImageIO.read(url);
                    catch(MalformedURLException mue)
                      System.err.println("url: " + mue.getMessage());
                    catch(IOException ioe)
                      System.err.println("read: " + ioe.getMessage());
               //return the array of images
             return images;
          }And this is where I draw the images:
           public class DiceImage extends JPanel
             private int x, y;
             private int width = 500, height = 150;
             private BufferedImage[] image;
             private int die1, die2;
          //create constructor and pass in image array     
              public DiceImage (int die1, int die2, BufferedImage[] image)
         this.die1 = die1;
         this.die2 = die2;
                         this.image = image;
          * Beginning of the paintWindow method
              public void paint(Graphics display)
         super.paint(display);
         //draw images in vending machine 3D box
                          x = 75;  //center the to images evenly
                          y = 10;  //10 pixels down from the top of the panel
         display.drawImage(image[die1], x, y, this);
         display.drawImage(image[die2], x + 200, y, this);                                   
             } // end paint
          //sets the preferred size for the item box
              public Dimension getPreferredSize()
                return(new Dimension(width, height));
          } //end of class   Let me know if you need any other snippets of code. I'm new to Java so please be gentle!

    I just don't know how to get the drawImages() to redraw using different images.display.drawImage(image[die1], x, y, this);
    display.drawImage(image[die2], x + 200, y, this);     
    In your paint method you are specifying the image to be drawn based on the values of die1 and die2. So if you want to draw a different image then you need to change the value of these two variables. So you need a method that changes these values.

  • Why Graphics.drawImage() can't work?

    Hi Veterans,
    I met some problems when I create an image by calling the Graphics.drawImage() method. Firstly, I created an off-screen image by calling the method frame.createImage(800, 640), then I was drawing some graphical elements on the the graphics acquired from the offscreen image, like drawString(), drawLine. And the most important step is as follows, I want to append another image from the file system to the current one by calling drawImage(Image img, int x, int y, ImageObserver frame), but it can't work, I got the appended image by calling Toolkit.getDefaultToolkit().createImage("D:\\abc.gif"). But I am not sure if it is a correct way to get an image from the file system. After that, I will use a 3rd party utitliy to generate new gif image. But when I view the new generated image, it only include the grahpical elements I drew by drawString(), drawLine, and the drawImage() seems can't work. Why?
    I post the code snippet for reference.
    Any help is appreciated!
                   frame=new Frame();
                   frame.addNotify();
                   Image offscreen = frame.createImage(800, 800);
                   g = (Graphics2D) offscreen.getGraphics();
                   g.setFont(new Font("Dialog",Font.PLAIN,12));
                   g.drawString("Owner ID:",10,10);
                   g.drawString("2238",90,10);
                   g.drawString("Order No.:",10,40);
                   Image image = Toolkit.getDefaultToolkit().createImage("D:\\barcode.gif");
                   System.out.println("[Image Width:] " + image.getWidth(frame)); //the output is -1, why?
    g.drawImage(image, 0, 0, frame); //seems can't work

    This isn't right. The Toolkit returned by getDefaultToolkit has an implementation for all these methods. The issue here is that you are calling getWidth on the Image before the Image has been loaded from your gif file. What you need to do is to call getWidth(ImageObserver) and then, if the width comes back as -1 wait for the ImageObserver to notify you that it has loaded the width attribute of the image. Take a look at
    http://java.sun.com/docs/books/tutorial/uiswing/painting/loadingImages.html
    Huw

  • Graphics.drawImage() problem

    Hi,
    I am trying to draw an image to the screen.
    Here is my code:
    public void paintArrowButtonForeground(SynthContext context, Graphics g,
                   int x, int y, int w, int h, int direction) {
              if (direction == SwingUtilities.SOUTH) {
                   if (image == null) {
                        image = Toolkit.getDefaultToolkit().getImage(
                                  this.getClass().getResource(UIManager.getString("Arrow.8x8.down")));
                   g.drawImage(image, x + image.getWidth(context.getComponent()) / 2,
                             y + image.getHeight(context.getComponent()) / 2,
                             (JButton) context.getComponent());
    I get image but it does not &#1072;ppear on screen.
    Can some one tell me what is wrong?
    Thank you in advance

    First thing's first...
    Using Toolkit.getImage() doesn't load the image, it starts loading the image. You normally use a MediaTracker to make sure that the image is loaded.
    Second thing's..., well, second...
    It is generally a bad idea to load images in the paint method. You should load the images needed for the class in the constructor, maybe or some other thread or someplace else before they are need in the paint method.

  • Bundles for Image Explorer & ZISWIN.exe fail in Windows 8.1

    ZCM version 11.3.1.39328, building Windows 8.1 workstation image, and testing existing bundles in the new OS. Both Image Explorer and ZISWIN fail. Image Explorer simply does not appear to run. ZISWIN runs but gives no information, indicating only that the user (an administrator) does not have the rights to view the ISD.
    If I browse to ZISWIN.exe and double-click it, I get the same thing. If I right-click it and "run as administrator" it works. However, you don't get "run as administrator" as an option when you right-click a NAL shortcut, you just get Open and Properties.
    Image Explorer is similar, but more peculiar. If I double-click zmgexp.bat, I get a bunch of errors about Java being missing. If I right-click zmgexp.bat and choose "run as administrator" I get a different bunch of errors also complaining about Java. If I open up an admin Command Prompt and run zmgexp.bat from within that, then it works.
    So, my question is this: Has anyone found a way to build bundles that work in Windows 8.1 for applications which depend upon running in the protected administrative environment?

    Running the Bundle as "Dynamic Administrator" should bypass UAC.
    Sometimes you may need to work with the zmgexp.bat to make sure that
    JAVA is properly located.
    On 10/16/2014 2:26 PM, kennolson wrote:
    >
    > ZCM version 11.3.1.39328, building Windows 8.1 workstation image, and
    > testing existing bundles in the new OS. Both Image Explorer and ZISWIN
    > fail. Image Explorer simply does not appear to run. ZISWIN runs but
    > gives no information, indicating only that the user (an administrator)
    > does not have the rights to view the ISD.
    >
    > If I browse to ZISWIN.exe and double-click it, I get the same thing. If
    > I right-click it and "run as administrator" it works. However, you don't
    > get "run as administrator" as an option when you right-click a NAL
    > shortcut, you just get Open and Properties.
    >
    > Image Explorer is similar, but more peculiar. If I double-click
    > zmgexp.bat, I get a bunch of errors about Java being missing. If I
    > right-click zmgexp.bat and choose "run as administrator" I get a
    > different bunch of errors also complaining about Java. If I open up an
    > admin Command Prompt and run zmgexp.bat from within that, then it
    > works.
    >
    > So, my question is this: Has anyone found a way to build bundles that
    > work in Windows 8.1 for applications which depend upon running in the
    > protected administrative environment?
    >
    >
    Going to Brainshare 2014?
    http://www.brainshare.com
    Use Registration Code "nvlcwilson" for $300 off!
    Craig Wilson - MCNE, MCSE, CCNA
    Novell Technical Support Engineer
    Novell does not officially monitor these forums.
    Suggestions/Opinions/Statements made by me are solely my own.
    These thoughts may not be shared by either Novell or any rational human.

  • Graphics and Images in Pages Templates

    Does anyone know if and where to find the graphics and images used in the Pages templates? I have noticed several "backgrounds" and other .jpgs that I would like to use when creating a new document but instead of copying and pasting all the time it would be nice to just know where the files are located on the computer. Can anyone inform me if i'm just missing them completely or if this is an impossible task?

    It is different for different versions of Pages. Which version do you have?

  • Graphics and images look wrong in Safari 4.0.3

    Hello
    Since upgrading to Safari 4.0.3 graphics and images in websites look low quality. As if they are being rendered with 256 colours or they are heavily compressed. The strange thing is that about a week ago the problem disappeared and everything looked sharp and great, I ran the new version of Cocktail last night and now the problem is back! Could be a coincidence but either way I can't fix it.
    Any advice would be appreciated
    Andy

    Greetings,
    Caches cannot be emptied automatically, nor can Web Page Previews, which is used for the Top Sites and Cover Flow features in Safari. You can empty those folders, but Web Page Previews will simply be refreshed with new images as you browse.
    If you don't want to use the Top Sites or Cover Flow features in Safari 4.0.3, you can disable it completely, and then you could empty those folders (com.apple.Safari and Web Page Previews) and then Lock the folders so any cache files from browsing would be deleted when you quit Safari.

  • Images not being Observed

    I've a simple applet class, a sample from a book. One line is this:
    g2d.drawImage(image, AffineTransform.getTranslateInstance(random.nextInt()%getSize().getWidth(), random.nextInt()%getSize().getHeight()), this);
    However, it doesn't accept my applet's ImageObserver or something, because when it can't compile it shows the last argument simply as 'BufferedImageTest' (that's the name of the class).
    Any ideas? Need to see the rest of the code? Uh... yeah. Thanks.l

    Yeah, a little more code would be helpful...
    1st, does your class implement ImageObesrver, and have all the methods required by that interface?
    2nd What specific error are you getting? Maybe paste that...

  • Image Capture in Lion fails to invert orientation of image from scanner

    I have been using Image Capture for scanning documents for awhile, and I often feed the documents in from the bottom.  Feeding this way requires that I select an option that inverts the final image.  Since upgrading to Lion, the inversion option fails.  I have a duplex scanner, and the image inversion option only fails on the odd pages, not the even (duplex) pages scanned.  When I do not have the duplex option selected, the inversion fails on all pages. 
    This seems like a quick bug fix for Apple.

    I have a solution. Its a workaround but it works pretty well. I made an Automator script that will combine PDFs in that are a folder. It will sort the individual PDF pages by creation date in descending order so that the result is in the order that was scanned.
    Scan the documents through your scanner's feeder and select "Duplex" if you have it. But do not select "Combine into single document." Put all the scanned PDFs in a new folder. Once all the scanning is done, run the app and it will ask you for the folder. Simply select the folder and a newly combined PDF will appear on your Desktop.
    Download the automator script from my dropbox link. The zip file contains both the app and the automator file in case you want to tinker with it. Cheers.
    https://dl.dropboxusercontent.com/u/2436819/Combine%20PDF.zip

  • Picked the "try" button for Photoshop and got an error "update failed" contact customer service (49) What do i need to do?

    Picked the "try" button for Photoshop and got an error "update failed" contact customer service (49) What do i need to do?

    Troyb50915784 for information on how to resolve Error 49 please see Error downloading and installing Creative Cloud application.  You are welcome to update this discussion if you have any questions regarding the steps listed within the discussion.

  • Suppression d'objets transparents (images intégrées) dans acrobat pro

    Bonjour à tous,
    J'ai réalisé la numérisation d'articles composés de textes et de photos (PDF image) que j'ai ensuite passé à l'OCR d'acrobat pro pour en faire des PDF avec le plain texte en vue d'une utilisation dans un moteur de recherche (jusqu'ici aucun problème !).
    Ces PDF sont ensuite intégré dans un composant ADOBE : acrobat viewer.
    Le problème que nous rencontrons est que ce composant n'affiche pas les images des articles (un rectangle noir se positionne au dessus de la photo).
    En vérifiant le contrôle en amont j'ai l'impression que l'OCR a rajouté un calque transparent de l'image au dessus de chaque image.
    En les supprimant manuellement avec l'outil modification avancée d'objets, on arrive à les visionner correctement dans le composant.
    Néanmoins j'ai plus de 300 articles à reprendre avec des masques placés un peu partout.
    Existe t'il donc un traitement par lot qui me permettrait d'automatiser la suppression de ces masques ?
    Voici l'affichage que j'ai de mon contrôle en amont :
    Merci de votre aide !
    Cordialement
    Djedai

    In Acrobat you can do a search for a word, but there is no search and replace. This type of editing is outside the scope of what Acrobat is designed for. Acrobat is not really and editor, but the editing features are provided for minor emergency repairs of a PDF. These editing features are rather cumbersome to use effectively.

  • SetRowHeight(int row,int height) fails

    Hi!
    I have a problem when I want to resize a row to a new height using the method
    setRowHeight(int row,int height)this don't do nothing!
    I'm using the example of a special JTable to merge cells wich is avaiable in http://codeguru.earthweb.com/java/articles/139.shtml
    I try to look in the code of this example, but I can't find the problem.
    I'm not using the merge method in the row I want to resize, so it should be working.
    If someone could help me I appreciate.
    Thanks in advance.

    From what I can tell from looking at the source code for MultiSpanCellTableUI, the paint method draws the cell rects using the general row height (ie table.getRowHeight() ) instead of the row specific height (table.getRowHeight(int row)). This could be a design flaw. You could attempt making the change in source code and see what results you get.
    ICE

  • After Firefox 4.0 beta installed after Int.Explorer failed, my favorites disappeared

    Whenever I opened the Drudge Report on Yahoo there was an error message at bottom site. I phoned Norton and I was referred to iyogi. I was told that I had 2619 registry errors, and they removed all but one, which resulted from Internet Explorer 7. I was told the only way to avoid the problem was to use Mozilla Firefox. That worked as to the Drudge problem but my Favorite list disappeared. I have limited tech skills, so I was unable to restore that Favorite list. Is there a way that list can be reinstalled.

    Click on the Firefox button then select Options to open the Options dialog. Now go to the Sync panel for the option to setup a new account.

  • Graphics.drawImage not using specified background color

    Thanks to everyone in advance -
    I have created an image resizing class, with a crop method. The cropping works great, the issue that I am having is the background color that i specify in the drawImage function of Graphics is not working correctly, it defaults to black as the background regardless of what I supply (in this case Color.WHITE). Also, the overlaying image or top most image (comes from a file) is being inverted(i think it is) or otherwise discolored. Here is the code below that I am working with:
    Thanks,
    Sam
                   public void Crop(int Height, int Width, int SourceX, int SourceY) throws Exception {
                        //output height and width
                        int OutputWidth = this.OutputImage.getWidth();
                        int OutputHeight = this.OutputImage.getHeight();
                        //create output streams
                        ByteArrayOutputStream MyByteArrayOutputStream = new ByteArrayOutputStream();
                        MemoryCacheImageOutputStream MyMemoryCacheImageOutputStream = new MemoryCacheImageOutputStream(MyByteArrayOutputStream);
                        //Create a new  BufferedImage
                        BufferedImage NewImage = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_ARGB);
                        Graphics MyGraphics = NewImage.createGraphics();
                        MyGraphics.drawImage(this.OutputImage, -SourceX, -SourceY, OutputWidth, OutputHeight, Color.WHITE, null);
                        // Get Writer and set compression
                        Iterator MyIterator = ImageIO.getImageWritersByFormatName("PNG");
                        if(MyIterator.hasNext()) {
                             //get image writer
                             ImageWriter MyImageWriter = (ImageWriter)MyIterator.next();
                             //get params
                             ImageWriteParam MyImageWriteParam = MyImageWriter.getDefaultWriteParam();
                             //set outputstream
                             MyImageWriter.setOutput(MyMemoryCacheImageOutputStream);
                             //create new ioimage
                             IIOImage MyIIOImage = new IIOImage(NewImage, null, null);
                             //write new image
                             MyImageWriter.write(null, MyIIOImage, MyImageWriteParam);
                        //convert output stream back to inputstream
                        ByteArrayInputStream MyByteArrayInputStream = new ByteArrayInputStream(MyByteArrayOutputStream.toByteArray());
                        MemoryCacheImageInputStream MyMemoryCacheImageInputStream = new MemoryCacheImageInputStream(MyByteArrayInputStream);
                        //resassign as a buffered image
                        this.OutputImage = ImageIO.read(MyMemoryCacheImageInputStream);
                   }

    Thanks for all your help!
    Here is the solution, notice the clear rect:
                   public void Crop(int Height, int Width, int SourceX, int SourceY) throws Exception {
                        //output height and width
                        int OutputWidth = this.OutputImage.getWidth();
                        int OutputHeight = this.OutputImage.getHeight();
                        //Create a new BufferedImage
                        BufferedImage NewImage = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB);
                        //create new grapics
                        Graphics2D MyGraphics = NewImage.createGraphics();
                        //set background
                        MyGraphics.setBackground(Color.decode(this.BackgroundColor));
                        //clear rect
                        MyGraphics.clearRect(0, 0, Width, Height);
                        //draw image
                        MyGraphics.drawImage(this.OutputImage, -SourceX, -SourceY, OutputWidth, OutputHeight, null, null);
                        //dispose graphics
                        MyGraphics.dispose();
                        //resassign as a buffered image
                        this.OutputImage = NewImage;
                   }

  • Mbp crash with graphical bug [Image attached]

    My Mbp is the model MacBookPro8.2 series, quad-core i7 2.4 15"
    I recently change my ram from the basic 4 gb to 16 gb. When it crashed initially I thought it was the ram. It turns out one my of my ram failed the memtest.
    I changed my ram and it still happened. This time I changed back to my original ram and it happen again.
    Attached is the image I took with my phone.
    https://dl.dropboxusercontent.com/u/3941713/Crash.jpg
    Any idea what is wrong and what I should do with this ?

    Graphic system is failing or the bad RAM corrupted the hard drive.
    Startup the system with the Command + Option/Alt + r keys held down until you see a globe on the screen.
    That will boot the system from across the internet from the Apple servers, taking your hard drive out of the picture.
    If you still get the same screen image, graphic corruption, then it is the graphics system problem. If you don't get that same problem then it is your hard drive that is corrupted.

Maybe you are looking for