Changing a Graphics2D object into a BufferedImage

Well subject says it all really. At some point in my code I extract a Graphics2D object from another object, and I'd like to store it as a BufferedImage. The code below does almost what i want, but not quite.
BufferedImage img;
GraphicsConfiguration gc = this.getGraphicsConfiguration();
this.img = gc.createCompatibleImage(getWidth(), getHeight(), BufferedImage.OPAQUE);
Graphics2D g2d = img.createGraphics();
This is the only hint I've been finding around the forums, and it works well if you just want to draw new drawings on a BufferedImage. However, I have a Graphics2D object that already contains alot of graphics, and I want to copy this into a BufferedImage. I can't seem to find a way to do this no matter where i look.
Any help would be appreciated.

reading through alot of code will be alot more work than a simple explanation of the problemA good SSCCE is many times easier to understand than a description.
That said, if I understand what you are trying, I assume you have a paintComponent override in nr1 that has a drawImage statement, and you want to obtain a part of that image in nr2 which is in a different class, to a BufferedImage in the same class as nr2.
If that's it, you can construct a BufferedImage of appropriate size and call the paintComponent method of nr1 with the Graphics reference of the BufferedImage, translated or otherwise transformed if necessary, to paint the panel's painting on the BufferedImage. Something like (in the class containing nr2)
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics());
g.translate(x, y); // optional
g.setClip(x1, y1, w1, h1); // optional
nr1.paintComponent(g);Note that you need a reference to panel nr1 in the class containing nr2.
Now (even if this is not what you needed) which was easier to understand -- the description above or the code? So if that's not it, don't expect anything more without a SSCCE which only demonstrates the problem faced -- not 500 lines of code that have nothing to do with the problem.
luck, db

Similar Messages

  • How to turn a graphics2D object into a BufferedImage

    Is there a simple way to take a Graphics 2D I have
    drawn and turn it into a BufferedImage?
    MArk

    OK, I understand now. First of all, a subimage has to be rectangular. You can't get a subimage that's an irregular shape. If you want a transparent background, we'll approach that later. First:
    // Create a BufferedImage for your original image.
    BufferedImage wholeImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = offScreen.createGraphics();
    // Set the clip region to draw in.
    g2.setClip(...);
    // Draw your entire picture to the offscreen image.
    g2.draw(...);
    // Now we want a bounding box for your clipped region.
    Rectangle clipRect = g2.getClipBounds();
    // Get a subimage from your original image that contains the clipped region.
    BufferedImage clippedImage = wholeImage.getSubimage(clipRect.getX(), clipRect.getY(), clipRect.getWidth(), clipRect.getHeight());Now you have a subimage that has the proper bounds to contain your clipped image in the smallest rectangle possible. The second image can be written to disk. The TYPE_INT_ARGB implies an alpha channel that gives you a transparent background so there's no bounding "square" wherever you decide to draw your subimage. Does this help?
    Michael Bishop

  • Merging Two Graphics2D objects into one

    Is it possible to accomplish this:
    1) have a method in class A that returns a Graphics2D object
    2) have a method in class B that returns a Graphics2D object
    3) have class C call both class A's and class B's methods that return Graphics2D objects
    4) lay those two Graphics2D objects into a new Graphics2D object within a component's paint(Graphic g) method
    What I am trying to do is a lot like a Viso diagram, that is drag a graphic onto another graphic x numberof times and perform some kind of layering technique.
    Thanks

    Why don't you pass a graphics 2D into each method, and get method to draw onto that. Then it becomes very simple to combine each.
    MArk

  • Saving back from CC17 to CS6 changes all complicated brushes into expanded objects.

    saving back from CC17 to CS6 changes all complicated brushes into expanded objects. Also brushes vanished from brush pallet

    http://helpx.adobe.com/illustrator/using/whats-new-17-0.html#Images%20in%20brushes
    Since the Brushes were rewritten for CC, backsaving them (as well as other items) will cause them to be expanded. No way around it.

  • How do I change the background color of a BufferedImage?

    I have a program and basically what I am doing is drawing on a BufferedImage object and then painting that BufferedImage object onto the panel. By default, the background is black and it draws in white. I am easily able to change the colour for drawing by doing g2.setColor(Color.RED) for example where g2 is the Graphics2D object created by image.createGraphics(). I tried g2.setBackground(Color.WHITE) and that did not work.
    If more information is needed, just ask.
    Any help in changing the background colour of the BufferedImage would be greatly appreciated!
    Thanks in advance!

    Here is a mini-code with comments explaining my trouble:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TestBuff extends JPanel
        Graphics2D g2;
        BufferedImage image;
        public TestBuff()
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setSize(800,800);
            frame.add(this);
            frame.setVisible(true);
            image = new BufferedImage(800,800,BufferedImage.TYPE_INT_RGB);
            g2 = image.createGraphics();
            g2.setBackground(Color.RED); // I am setting the background colour here
        protected void paintComponent(Graphics g)
            g.drawImage(image, 0, 0, g2.getBackground(), this); // Why is this black instead of red?
        public static void main(String[] args)
            new TestBuff();
    }

  • Load a redrawn image into a JLabel and save it into a BufferedImage?

    Hello, I'm doing a small application to rotate an image, it works, but I'd like to show it into a JLabel that I added, and also store the converted image into a BufferedImage to save it into a database, this is what I have so far:
    public void getImage() {
    try{
    db_connection connect = new db_connection();
    Connection conn = connect.getConnection();
    Statement stmt = conn.createStatement();
    sql = "SELECT image " +
    "FROM image_upload " +
    "WHERE image_id = 1";
    rset = stmt.executeQuery(sql);
    if(rset.next()){
    img1 = rset.getBinaryStream(1);
    buffImage = ImageIO.read(img1);
    rset.close();
    } catch(Exception e){
    System.out.println(e);
    public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    ImageIcon imgIcon = new ImageIcon(buffImage);
    AffineTransform tx = AffineTransform.getRotateInstance(rotacion, imgIcon.getIconWidth()/2, imgIcon.getIconHeight()/2);
    g2.drawImage(imgIcon.getImage(), tx, this);
    jLabel1.setIcon(imgIcon);
    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    setRotacion(getRotacion() + 1.5707963249999999);
    repaint();
    I get the image from a db, then using the paint() method I rotate the image, it works, but the new image is outside of the JLabel and I don't know how to assign the new one into the JLabel (like overwritting the original) and also how to store the new image into a BufferedImage to upload it into the database converted, thanks in advanced, any help would be appreciated, thanks!!
    Edited by: saman0suke on 25-dic-2011 14:07
    Edited by: saman0suke on 25-dic-2011 15:08

    I was able already to fill the JLabel with the modified content, just by creating a new BufferedImage, then create this one into a Graphics2D object and the drawing the image into it, last part, inserting the modified image into the database, so far, so good, thanks!
    EDIT: Ok, basic functionality is ok, I can rotate the image using AffineTransform class, and I can save it to the database and being displayed into a JLabel, now, there's a problem, the image for this example is 200 width and 184 height, but when I rotate it the width can be 184 and the height 200 depending on the position, but the BufferedImage that I create always read from original saved image:
    bimage = new BufferedImage(buffImage.getWidth(), buffImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Is there a way that I can tell BufferedImage new width and height after rotate it? :( as far as I understand this cannot be done because before the image bein rotated the bufferedImage is already created and, even being able to do it how can I get width and height from rotated image? thanks!
    Edited by: saman0suke on 25-dic-2011 19:40

  • Error : while converting a WD ABAP object into SAP Transaction

    Hi,
    I am trying to converting a WD ABAP object into SAP Transaction but i am getting the following error while executing the transaction :
    Network Access Message: The page cannot be displayed
    Technical Information (for Support personnel)
    Error Code: 502 Proxy Error. The specified Secure Sockets Layer (SSL) port is not allowed. ISA Server is not configured to allow SSL requests from this port. Most Web browsers use port 443 for SSL requests. (12204)
    IP Address: 10.114.6.144
    Date: 4/7/2011 10:41:
    Please help.

    > ISA Server is not configured to allow SSL requests from this port. Most Web browsers use port 443 for SSL requests. (12204)
    This seems to be your specific network configuration.  It seems that your corporate network is blocking HTTPS requests which don't use port 443. Your ABAP system is configured to use a port other than 443. Either talk to your basis admins about changing your ABAP system configuration to use port 443 or talk to your network administrators to allow whichever port the ABAP system is running on.

  • Import of SAP Objects into Integration Repository in XI 3.0

    Hi all,
    I am not able to import SAP objects into the Integration Repository in XI 3.0. This option is under any Software Component  Version. I have selected the radio button "Import of RFC and IDoc interfaces from SAP systems permitted", in the Software  Component Version settings. After the connection data is specified for the SAP system nothing appears under the IDoc, Whereas  the import of RFCs is successfull.
    We also have another installation of SAP XI 3.0, here this option is working properly. Can anyone tell me what is the  problem, is is there something else to be configured inorder to do this.
    Best regards,
    Norway

    Hi Stephan
    Thank you for your answer. We have followed your instructions but did only get half a success. Here is what we have done:
    1) Created "External Definitions" for all related xsd-files with the same name as the xsd-filename and in our own namespace. Our namespace is different from those specified in the xsd-files. We have not change the namespaces in the xsd-files.
    2) Maintained the "source"-field with the name for the xsd-file and not the url as specified in our answer. When we used the filename only we got a value the field "name" in the "External References".
    3) We made a message mapping and imported the "top-level-xsd-element" from the "External Definition". This resulted in only the top level element and nothing else. What we expected was the possibility to drill down through the complete structure.
    What did we doe wrong? Perhaps I could talk you into spending 10 min. and try it your self? This url leads to a zip file with all the related xsd files: http://rep.oio.dk/ubl/xml/schemas/0p71/documentation/resources.html
    Do you know if it will be possible to make references across namespaces in a later version of XI?
    Regards
    Christian

  • Material delta changes are not flowing into CRM

    Dear All,
    material delta changes are not flowing into CRM, because the product hierarchy on material has been changed to a new product hierarchy. I do not want to download again the object DNL_CUST_PROD1 because it maight cause inconstancies in CRM. (I have already defined some z product hierarchies in CRM)
    Do I need to create the new product hierarchy also in CRM manually?
    Appreciate any inputs
    Raj

    Hi Raj,
    Use the transacrion R3AR2 to create a z object for DNL_CUST_PROD1 and assign DNL_CUST_PROD1 as the object name
    Then in request detail screen for new z object enter the details like table name (T179 in your case) and the name of the product hierarchy that you want to bring in. Save the transaction
    Then use the transaction R3AR4 to initiate the download for your new z object as you normally do in R3AS.
    Then go to SMW01 and reprosess the struck Bdoc.
    Reward points if helps,
    Regards,
    Paul Kondaveeti

  • Cannot open PDFs inserted as objects into Excel.

    Two-part question.  I know this has been addressed before, but the solutions are not working for me.
    I have Adobe Acrobat 9 Pro and Adobe Reader XI.  When inserting a PDF document as an object into Excel, it will not allow me to insert the icon/object from the "Create New" option.  I get one of two error messages: 'Cannot insert object'  or 'Cannot start the soruce application for this object'.  I am able to insert the PDF icon/object if I insert from the "Create from file" option. (Please note I cannot always link to the PDF, as some spreadsheets are sent out externally and will not have access.)
    Once I am finally able to insert the document as an object, I can open and view the PDF.  However, when I close the spreadsheet and re-open it, if I try to open the PDF document again, I get this error message again: 'Cannot start the soruce application for this object'.
    I have changed my preference to disable the Protected Mode at startup and this issue is still happening.  VERY frustrating.  I never encountered this is past versions of Adobe and all previous suggestions are not fixing the issue.  Does anyone have any insight or know of an update to fix this issue?  Is this an Adobe issue or a Microsoft Office issue?

    Hi Jerry,
    Can you check the similar thread
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/d554e88c-d72f-46b0-8b1a-2f2024fcb9c0/i-e-8-browser-wont-open-pdf-file-returned-from-sharepoint-2010-search?forum=sharepointadminprevious
    My Blog- http://www.sharepoint-journey.com|
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful

  • How to change attributes of Objects of all windows in a MDI application

    Hi,
    I have a MDI application to draw Object. In these MDI windows I can modify attributes of Object like color, size... Now I want to create an option, when the user change or modifies attribute of Objects in a window, so it allow to change attributes of objects in all windows. I don't know how I can do it, please help me. Thanks

    Allow your objects to alias mutable attribute objects.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    import java.util.List;
    public class Example extends JPanel {
        private List bangles = new ArrayList();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            for(Iterator j=bangles.iterator(); j.hasNext(); )
                ((Bangle)j.next()).paint(g2);
        public void addBangle(Bangle bangle) {
            bangles.add(bangle);
            repaint();
        public static void main(String[] args) {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            Example app = new Example();
            JFrame f = new JFrame("Example");
            Container cp = f.getContentPane();
            cp.add(app, BorderLayout.CENTER);
            cp.add(Controller.create(app), BorderLayout.NORTH);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(800,600);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class Controller {
        private Shade shade1 = new Shade(Color.GREEN), shade2 = new Shade(Color.RED), currentShade=shade1;
        private Example modelView;
        public static JComponent create(Example modelView) {
            return new Controller(modelView).createUI();
        private Controller(final Example modelView) {
            this.modelView = modelView;
            modelView.addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent evt) {
                    Rectangle shape = new Rectangle(evt.getX(), evt.getY(), 20, 20);
                    modelView.addBangle(new Bangle(shape, currentShade));
        private JComponent createUI() {
            ButtonGroup bg = new ButtonGroup();
            final JToolBar tb = new JToolBar();
            final JRadioButton rb1 = createRadio("Shade 1", true,  shade1, bg, tb);
            final JRadioButton rb2 = createRadio("Shade 2", false, shade2, bg, tb);
            JButton btn = new JButton("Change color of selected shade");
            btn.setContentAreaFilled(false);
            btn.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    Color newColor = JColorChooser.showDialog(tb, "Choose new color", currentShade.getColor());
                    if (newColor != null) {
                        currentShade.setColor(newColor);
                        if (currentShade == shade1)
                            rb1.setForeground(newColor);
                        else
                            rb2.setForeground(newColor);
            tb.add(btn);
            return tb;
        private JRadioButton createRadio(String text, boolean selected, final Shade shade, ButtonGroup bg, JToolBar tb) {
            JRadioButton rb = new JRadioButton(text, selected);
            rb.setContentAreaFilled(false);
            rb.setForeground(shade.getColor());
            rb.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    currentShade = shade;
            tb.add(rb);
            return rb;
    class Bangle {
        private Shape shape;
        private Shade shade;
        public Bangle(Shape shape, Shade shade) {
            this.shape = shape;
            this.shade = shade;
        public void paint(Graphics2D g2) {
            g2.setColor(shade.getColor());
            g2.draw(shape);
    class Shade {
        private Color color;
        public Shade(Color color) {
            this.color = color;
        public Color getColor() {
            return color;
        public void setColor(Color color) {
            this.color = color;
    }

  • Pasting multiple objects into frame

    Greetings everyone
    I was wondering if someone could shed some light on how to best paste multiple objects into a single frame.
    Mainly, I'm trying to nest objects that form a part of a newspaper article header; since it's a design element that keeps repeating with each single article I don't want to spend time with manually positioning the elements each time--it's time consuming and prone to sloppiness.
    Unfortunately, the base frame will have about three objects that need to be nested within it. Once I paste one object into a frame, the next time I do `Paste into`--the content (previously pasted object in this case) just gets overridden.
    I've read that, to paste multiple objects into a single frame, one should group the objects first. Now this works pretty well for getting them into the frame, but leaves me with no options to position them relative to the frame. I can't move or position an object individually and I have no option to ungroup them once they've been pasted.
    Here's a small mock-up to depict my peculiar predicament:
    Ideally, I'm aiming to have the main header frame to fit the content of the nested objects and for it to be flexible enough that I can quickly span it across multiple columns as per article requirements.

    !kRON wrote:
    For items that are part of the group, their (X,Y) location coordinates are relative to the document--neither to the group nor the parent frame. The group itself has coordinates that are relative to the parent frame (X+ offset, Y+ offset). I can select the group and the parent frame and use the align to selection options. For individual items, I cannot make a selection of both them and the frame, only between items that are part of a group. I loose options to align an individual item relative to the parent frame, which means I have to drag them around and rely on smart guides.
    I've tinkered around some more and it'd appear it's not possible to lay out the elements as I imagined. So I have to resort to grouping the items that would form a frame and pasting them into a frame. If multiple frames have to be members of a single frame I'd have to group the frames and paste them into the single frame and so on.
    Based on my layout mock-up, I'd end up with 3 frames within the header frame:
    Article header
    Heading
    Article type
    Separator
    Article heading
    Title
    Footer
    Author
    Shape
    Based on experience, should I go with this or stick with the old fashined moving around of loose elements? Will it be a lot of work to maintain resizing and repositioning of the various items and their frames once I start changing the width and height of the header frame or will it save me some time?
    I'm not a working designer or production worker, so anything new takes me longer than I think it should, because I don't have a rich reservoir of quick methods at my fingertips.
    Your description above interested me, because I've been wrestling with the annoying limitations of manipulating and adding compound objects in anchored frames. For many situations, it's probably simplest to assemble each iteration of a compound object, that introduces a new element, outside the anchored frame, then group the elements and paste the grouped object into the anchored frame.
    However, the arrangement of elements in your example made me think that a table might be a workable solution. The answer I arrived at is "Yes, it's a solution, but it takes a while to set up." If it's reusable easily, then it might be worthwhile investing in a few experiments.
    I've attached a zipped idml interchange version of the file, and also a PDF.
    Here are some notes:
    * I created a table with three rows and three columns, no header or footer rows. Three columns because I thought I'd paste a vertical line into an inline anchored frame in the center cell of the top row, for the separator line. Later, I realized that defining the vertical cell rule as paper color would suffice, so I merged the two right cells on the top row to create a two-column row, with text in each cell and the vertical separator between them.
    * I merged all three cells on the second row into a single cell.
    * I merged the two right cells on the bottom row, but later, when I moved the cell rule to position the triangular graphic in the inline anchored frame in the right cell, it moved the vertical cell rule in the first row. So, I had to unmerge (or split) the cells, and cut/paste the triangular graphic's anchored frame into the rightmost cell. To position the anchored frame, I moved the vertical cell rule with Shift+Drag, to keep the table width unchanged.
    * I sampled the purple color with the eyedropper tool while cells were selected and the swatch panel was set to fill the selected object.
    * I didn't spend much time matching the type, as you can see. To position the text, I adjusted the cell margins in some cases, and left/right indention in some cases; I'm not sure which is more efficient in situations where there will be different amounts of text to fit. I didn't create cell styles or paragraph styles (BAH! Bad, bad, bad process) because I won't be repeating this stuff, but you probably will benefit greatly from defining styles for your repeating needs.
    * The triangular cut into the bottom row made it easy to manage creating and positioning the graphic. A non-geometrical object might be trickier. The triangle is a text frame, set to negative space above, so it overlaps the cell above it, enough to avoid a black gap.
    * Except for the vertical paper-colored divider line, all the cells have zero-width strokes.
    * I created the table in a text frame, that I fitted down to the size of the table, but I can't remember if I selected, copied, and pasted the text frame into the text flow to anchor it, or if I selected the table in the text frame, copied and pasted it into the flow. Not sure if it makes a difference in work efficiency.
    If I understand your general needs, this should work well for changing text and adjusting the column widths.
    HTH
    Regards,
    Peter Gold
    KnowHow ProServices

  • Best way to import all objects into work repository located on a new master respository

    Hi,
    We have two separate master repositories, one for all development work repositories (Development, ST, UAT, IAT), and one for Production.
    What would be the best approach to export and import all objects from the Dev Repository into the Prod Work Repository located on the Prod Master Repository.
    Internal Ids of all work repositories are different.
    We have tried putting everything into a solution and exporting that, but that did not work when we tried to import it.
    We successfully exported and imported a single scenario, however this is not very practical as we have over 500 scenarios.
    All suggestions welcome,
    Thanks,
    Nic

    Thanks,
    But we want to keep Dev Work Repositories separate to Prod Work Repositories on their respective Master Repositories.
    So our end result will have:
    1) All Development Work Repositories located in the Development Master Repository on the Development server.
    2) The Production Work Repository located on the Production Master Repository on the Production Server.
    3) The ability to update a Solution or similar in Development with all changes to any objects.
    4) The ability to import the Solution into the Prod Work Repo on the Prod Master Repo and execute via a load plan.
    Is this possible?

  • Conversion of object into integer

    hi
    How to convert Object into integer.
    I want to get value of JTable cell.So im doing
    for(int i=0;i<4i++)
    String value=(String) JTable.getValueAt(i,2);
    s.o.p("Table value :"+JTable.getValueAt(i,2));
    int changedValue=Integer.parseInt(Value);
    s.o.p("Changed value :"+value);
    }JTable.getValueAt(0,2) : 0
    JTable.getValueAt(1,2) : 0
    JTable.getValueAt(2,2) : 2
    JTable.getValueAt(3,2) : 4
    Theses are the respective values of the respective row positions
    Im able to get values of 1st row and 2nd row which are of 0 values
    But the value of third row and 4th row im gettin an exception
    java.lang.Integer cannot cast to java.lang.String
    please help anyone

    If the data in the model is of type Integer you can't cast it to String.
    You need to cast this to Integer and call intValue method to get as int.
    If you want further help post a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html] that demonstrates the problem.

  • BPM-  Change Standard Monitoring Object

    Hi,
    I have few queries in BPM:
    1). How to change a standard Montior?
         For example, if I want to change Monitoring Object Sales Document (KPSD0001) and add New Keyfigure or add a new
         selection parameter (eg. Plant) for a keyfigure. How do I do this??
    2) In which database table/Transaction can I see all the Standard Monitoring Objects available.
    3) How can I copy a standard Monitoring Object  into a Z Monitor and make the required Changes.
    Regards,
    Shalini Chauhan

    Hi Shalini
    1)As Ragu mentioned, it is not possible to change standard monitoring
      object. Code is already fixed to the selection parameter.
    2)It is stored in special way in satellite system. (Cluster table).
      So it is not easy to check it like via SE16.
      You can get list of available monitoring object and key figure from
      the list that is available in service market place.
      (You need authorization to access service market place).
      http://www.service.sap.com/bpm
      =>media library =>Customer Information
      =>Business Process & Interface Monitoring - Part 2
    3)As Ragu mentioned, I also recommend you to check customer exit
      development guide.
        http://www.service.sap.com/bpm
        =>media library =>Technical Information
        =>Technical Information
        =>Guide - Customer Exit
    Best Regards
    Keiji  Mishima

Maybe you are looking for