How to get (a part of) Graphics2D as an Image?

I have drawn something on a Graphics2D object. On another Graphics2D object, I want to draw just a part of the first Graphics2D object (subImage). To be able to call getSubimage() I need a BufferedImage. So how can I "convert" a Graphics2D to a BufferedImage?

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class SubTest {
    JTabbedPane tabbedPane;
    DemoGraphicPanel dgPanel;
    private void demonstrate(final Rectangle r) {
        tabbedPane.addTab("full image", new JPanel() {
            BufferedImage image = makeImage();
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, 0, 0, this);
        tabbedPane.addTab("clipped image", new JPanel() {
            BufferedImage image = makeClippedImage(r);
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, r.x, r.y, this);
        tabbedPane.addTab("clipped draw", new JPanel() {
            BufferedImage image = makeImage();
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setClip(r);
                g.drawImage(image, 0, 0, this);
                //g.setColor(Color.blue);
                //((Graphics2D)g).draw(r);
        tabbedPane.addTab("subImage", new JPanel() {
            BufferedImage image = makeImage().getSubimage(r.x, r.y,
                                                  r.width, r.height);
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, r.x, r.y, this);
        // Resize to accomodate multiple rows of tabs.
        //((Window)tabbedPane.getTopLevelAncestor()).pack();
        SwingUtilities.windowForComponent(tabbedPane).pack();
    private BufferedImage makeImage() {
        int w = dgPanel.getWidth();
        int h = dgPanel.getHeight();
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(w, h, type);
        Graphics2D g2 = image.createGraphics();
        dgPanel.paint(g2);
        g2.dispose();
        return image;
    private BufferedImage makeClippedImage(Rectangle r) {
        int w = r.width;
        int h = r.height;
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(w, h, type);
        Graphics2D g2 = image.createGraphics();
        g2.translate(-r.x, -r.y);
        dgPanel.paint(g2);
        g2.dispose();
        return image;
    private JTabbedPane getContent(Rectangle r) {
        dgPanel = new DemoGraphicPanel(r);
        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("original", dgPanel);
        return tabbedPane;
    public static void main(String[] args) {
        final Rectangle clip = new Rectangle(100, 100, 150, 150);
        final SubTest test = new SubTest();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(test.getContent(clip));
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
        // All events in single-file queue.
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                test.demonstrate(clip);
class DemoGraphicPanel extends JPanel {
    Rectangle r;
    Dimension size = new Dimension(400,400);
    DemoGraphicPanel(Rectangle r) {
        this.r = r;
        setBackground(new Color(240, 220, 220));
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = size.width;
        int h = size.height;
        g.setColor(Color.red);
        g.drawLine(0,0,w,h);
        g.setColor(Color.blue);
        g.drawLine(0,h,w,0);
        g.setColor(Color.red);
        g.drawRect(r.x, r.y, r.width-1, r.height-1);
    public Dimension getPreferredSize() {
        return size;
}

Similar Messages

  • How to get spisipic part of view in jframe

    Hello all.
    I wrote a project and run it on other comp with small screen. Now I can see only part of the Jframe.I added a scrollBar to Jframe and now I need to write to it a listener.
    My qustion is how to get spicific view from a jframe.
    Because a can get the value from the scrollBar so now I need to know what is the function to move view in jframe.
    thanks alot.
    please do not give me tutorial on scrollbar
    Edited by: vitaly87 on 00:24 27/04/2011
    Edited by: vitaly87 on 00:25 27/04/2011
    Edited by: vitaly87 on 00:31 27/04/2011

    vitaly87 wrote:
    ..plese do not give me tutoriol on scrollbarWhat about a tutorial on spelling?
    Edited by: Andrew Thompson on Apr 27, 2011 5:51 PM
    My qustion is how to get spicific view from a jframe.If you fixed that to something like..
    My question is how to get specific view from a JFrame.I could edit my reply to nothing - to save bandwidth for readers of the thread.

  • How to get RGB value from pixel of an image.

    hi, i need a little help... Is there any EASY way to get RGB value from point of an image? I searched javadoc but i only found very complex getRGB method working only with regions, and saving data into arrays.
    Is there any other way that can use for example image.getGraphics() (so, i mean to get RGB from point of Graphics object) ?
    Btw.: If you know, how Sprite.collidesWith(Sprite s, Boolean pixellevel) is working (with pixellevel = true), please write me. It could solve my problem too.
    Thanks

    Is there any other way that can use for example image.getGraphics() (so, i mean to get RGB from point of Graphics object) ?You can think of the graphics object like a pencil or paintbrush. Does a paintbrush know the color of the surface it is painting on? No.
    Btw.: If you know, how Sprite.collidesWith(Sprite s, Boolean pixellevel) is working (with pixellevel = true), please write me. It could solve my problem too.Download the reference implementation from this site and see for yourself.
    luck, db

  • How to get transparency scroll bar to view background image of canvas.

    HI, 
    How to get transparency to path in canvas to view background image in canvas using scroll bar control.?
    This is my present output:
    My Xaml Code:
    <Grid Height="auto" Name="grid1">
    <TabControl Background="Bisque">
    <TabItem Header="Tools">
    <Grid Height="1000" Width="1000" Name="grid">
    <Border BorderThickness="0.2" BorderBrush="Black" Height="820" Width="820" ClipToBounds="True" Margin="90,99,90,81"></Border>
    <Grid>
    <Button Content="Original Size" Height="23" Name="btn_Original" Width="75" Click="btnOriginalSizePosition" Margin="4,4,921,973" />
    <TextBox Height="20" HorizontalAlignment="Left" Margin="62,49,0,0" x:Name="txtNoOfZones" VerticalAlignment="Top" Width="49"
    MaxLength="2" PreviewTextInput="txtNoOfZones_PreviewTextInput"/>
    <TextBox Height="20" HorizontalAlignment="Right" Margin="0,71,890,0" x:Name="txtSec" VerticalAlignment="Top" Width="49" PreviewTextInput="txtSec_PreviewTextInput" MaxLength="3"/>
    <Button Content="OK" Height="32" HorizontalAlignment="Left" Margin="117,59,0,0" Name="btnNoOfZones" VerticalAlignment="Top" Width="39" Click="btnNoOfZones_Click" />
    <Label Content="Zone Number selected :" Height="28" HorizontalAlignment="Right" Margin="0,0,451,0" Name="lblZone" VerticalAlignment="Top" />
    <Label Content="Sector Number in selected Zone :" Height="28" HorizontalAlignment="Right" Margin="364,22,451,0" Name="lblSector" VerticalAlignment="Top" />
    <Label Content="Filled Color applied in selected sector :" Height="28" HorizontalAlignment="Right" Margin="336,44,451,0" Name="lblColor" VerticalAlignment="Top" />
    <Label HorizontalAlignment="Left" Margin="569,0,0,0" Name="lblZoneNumber" Height="28" VerticalAlignment="Top" />
    <Label Height="28" HorizontalAlignment="Left" Margin="569,22,0,0" Name="lblSectorNumber" VerticalAlignment="Top" />
    <Label Height="30" HorizontalAlignment="Left" Margin="569,44,0,0" Name="lblFillColor" VerticalAlignment="Top" FontWeight="Bold"/>
    <Label Content="Sectors :" Height="28" HorizontalAlignment="Left" Margin="7,67,0,905" Width="69" />
    <Label Content="Zones :" HorizontalAlignment="Left" Margin="13,44,0,928"/>
    <TextBlock Height="23" HorizontalAlignment="Left" Margin="4,32,0,0" Text="Change No.of Zones, sectors below and click OK button" VerticalAlignment="Top" Width="294" FontFamily="Cambria" FontSize="12" FontStyle="Italic" FontWeight="Bold" />
    <RadioButton Content="Single Sector" Height="16" HorizontalAlignment="Left" Margin="744,24,0,0" Name="rBtnSingleSector" VerticalAlignment="Top" GroupName="Selection"/>
    <RadioButton Content="Sector Zone" Height="16" HorizontalAlignment="Left" Margin="744,44,0,0" Name="rBtnSectorZone" VerticalAlignment="Top" GroupName="Selection"/>
    <RadioButton Content="Circular Zone" Height="16" HorizontalAlignment="Left" Margin="744,64,0,0" Name="rBtnCircularZone" VerticalAlignment="Top" GroupName="Selection"/>
    <RadioButton Content="Panning" Height="24" HorizontalAlignment="Left" Margin="744,4,0,0" Name="rBtnPanning" VerticalAlignment="Top" Width="74" GroupName="Selection"/>
    <Border x:Name="clipBorder" BorderBrush="Black" BorderThickness="0" ClipToBounds="True" Height="810" Width="810" Margin="95,104,95,86" CornerRadius="10">
    <Canvas x:Name="CanvasPanel" Height="800" Width="800" Background="Transparent" ClipToBounds="True"></Canvas>
    </Border>
    <RadioButton Content="Random Color" HorizontalAlignment="Left" Margin="868,5,0,979" Name="rdBtnRandomColor" GroupName="rdbtnGroupFillColor"/>
    <RadioButton Content="Red Color" Height="16" HorizontalAlignment="Left" Margin="868,24,0,0" Name="rdBtnRedColor" VerticalAlignment="Top" GroupName="rdbtnGroupFillColor" Foreground="#FFF81010" FontWeight="Bold" />
    <RadioButton Content="Green Color" Height="16" HorizontalAlignment="Left" Margin="868,44,0,0" Name="rdBtnGreenColor" VerticalAlignment="Top" GroupName="rdbtnGroupFillColor" Foreground="#FF175F17" FontWeight="Bold" />
    <RadioButton Content="Adjacent" Height="16" HorizontalAlignment="Left" Margin="435,81,0,0" Name="rdBtnAdjacent" VerticalAlignment="Top" GroupName="Selection" />
    </Grid>
    </Grid>
    </TabItem>
    <TabItem Header="Change Background">
    <Grid Height="1000" VerticalAlignment="Top" Background="Bisque">
    <Button Height="70" Width="70" Margin="6,1,892,929" Name="btnBrowseImage" Click="btnAll">
    <Image x:Name="browseIcon" Source="D:\WPF\Projects\TabControlVRI_18_12_2014\Images\img.png" MouseLeftButtonDown="Image_MouseLeftButtonDown_1"/>
    </Button>
    <Button Height="70" Width="70" Margin="92,1,806,929" Name="btnCenterPoint" Click="btnAll">
    <Image x:Name="centerIcon" Source="D:\WPF\Projects\TabControlVRI_18_12_2014\Images\center.jpg" Width="54" Height="48" />
    </Button>
    <Button Height="70" Width="70" Margin="179,1,719,929" Click="btnAll">
    <Image x:Name="boundaryIcon" Source="D:\WPF\Projects\TabControlVRI_18_12_2014\Images\Path_Simple.png" Height="44" Width="49" />
    </Button>
    <Image Name="imgBackground" Height="800" Width="800" MouseLeftButtonDown="imgBackground_MouseLeftButtonDown">
    </Image>
    </Grid>
    </TabItem>
    </TabControl>
    </Grid>
    C# code:
    OpenFileDialog op = new OpenFileDialog();
    ImageBrush ib = new ImageBrush();
    private void Image_MouseLeftButtonDown_1(object sender, RoutedEventArgs e)
    op.Title = "Select a picture";
    op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
    "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
    "Portable Network Graphic (*.png)|*.png";
    if (op.ShowDialog() == true)
    ib.ImageSource = new BitmapImage(new Uri(op.FileName));
    imgBackground.Source = new BitmapImage(new Uri(op.FileName));
    CanvasPanel.Background = ib;
    Please help me out to get transparency for path in canvas to view background image in canvas.
    The complete code is in below link:
    https://onedrive.live.com/redir?resid=876CFAE94C306176!112&authkey=!AC1sQIYwyoRYT_o&ithint=file%2crar
    Regards,
    Viswa.

    Hi ViswAmmu,
    >>Please help me out to get transparency for path in canvas to view background image in canvas.
    If I'm not misunderstanding, I think you just need to loop through all Canvas.Children and set Opacity property for them:
    private void Image_MouseLeftButtonDown_1(object sender, RoutedEventArgs e)
    //Loop through all children items
    foreach(UIElement v in CanvasPanel.Children)
    v.Opacity = 0;
    op.Title = "Select a picture";
    op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
    "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
    "Portable Network Graphic (*.png)|*.png";
    if (op.ShowDialog() == true)
    ib.ImageSource = new BitmapImage(new Uri(op.FileName));
    imgBackground.Source = new BitmapImage(new Uri(op.FileName));
    CanvasPanel.Background = ib;
    Screenshot:
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to get the Macbook app which sends camera images back if someone steals it

    There was a story run in a UK paper this week of someone who recovered their stolen Macbook because he had a programme on it that activated the camera when the laptop was in use, it then relayed the stills and moving pictues back to him and the theif was clearly identified!
    Anyone know how to get this??
    AJ

    http://www.orbicule.com/undercover/mac/index.html

  • How to get a part of the background image.

    Hi
    I have created a JPanel using paintComponent() and added it to the content pane of the JFrame. It consists of two colors blue and white. It consists of blue background color and on top of that a part of white background is also there. Now i want to place the components only on the white background. But still the components are getting placed on the blue one.Below is the code for creating the panel.
    public void paintComponent(Graphics g)
               try
                    Paint bckGrndPaint = new GradientPaint(200,0,new Color(5,62,95,255) ,200,
                                            500, new Color(226,226,224,255), true);
                    Graphics2D g1d = (Graphics2D)g;
                    g1d.setPaint(bckGrndPaint);
                    g1d.fillRect(0, 0, getWidth(), getHeight());
                    RoundRectangle2D r = new RoundRectangle2D.Float(20,20, getWidth()-60, getHeight()-60, 25,
                                  25);
                    g1d.setColor(Color.WHITE);
                    g1d.draw(r);
                    g1d.fill(r);
                                      }

    Hi,
    For this approach you should use two JPanels ... one for the blue part ... and the other for the white.
    So you can place the components only at the white part. The gradient paint may be splitted
    into two gradient paints. Without this you won't benefit from the
    layout manager ... and setting the components hard coded is not a nice idea...
    If you don't know how to use layouts take a look at this page.
    Olek

  • How to get a part of a string?

    Hi,
    I get the value of a field from  a database table as SAPKB70013.
    Now I just want to get the last two digits (ie. 13 ) of this value ansd pass it to another variable.
    How is it possible?

    Hi Harshit,
    First calculate the length of your string through STRLEN statement and then,
    use it with OFFSET.
    Kindly go through this link below:
    http://help.sap.com/saphelp_nw04/helpdata/EN/fc/eb341a358411d1829f0000e829fbfe/content.htm
    Hope it helps
    Regrds
    Mansi

  • How to get the page count of a tiff image:

    Hi,
      My process takes input (of document type) tiff image. I want to get the number of pages present in the tiff image into one of my process variables.
    How can I get that?
    Thanks,
    kc

    Hi
    I'v tried rennie1's way ,but I only get zero,my code is:
    rs.executeQuery("select count(*) from t_test");
    if (rs.next()) int rowCount=rs.getInt(1);
    I also tried barni's way ,but the method rs.last() and rs.beforeFirst() throw a same Exception
    I tried another way,the code is:
    while rs.next(){
    // Do nothing ,just move the cursour to the last row
    int rowCount=rs.getRow()
    However,the rowCount still equal zero
    Any help would be greatly apprecite!
    note:
    I get connection by DataSource's JNDI name from client, the Server is Weblogic Server 6, the DBMS is Oracle.

  • How to get scaled copy of bitmapData of an Image?

    For the class spark.components.Image
    I can access the bitmapData object (readonly) (unscaled).
    I know the scaling factors of the Image.
    How can I get a scaled version of the bitmapData?
    Thanks!

    This response on stackoverflow pretty much shows how I scale bitmaps when I need too.
    thttp://stackoverflow.com/questions/964495/what-is-the-best-way-to-resize-a-bitmapdata-obje ct

  • How to get coordinates of a ROI in an image in Labview

    Hi,
    I have a question regarding image processing in NI-IMAQ. I have
    Ni-IMAQ module available, soon I may acquire NI-Vision too. I have an
    image file and I would like to draw a rectangle as Region of Interest
    (ROI) and be able to get the coordinates of the pixels in the ROI or
    along the edges of the ROI. I tried to find vis for this operation. I
    was able to find vis which provides the pixel values but I could not
    find the vis for the above operation. Any information regarding
    solution to above problem or any good resources for learning Labview
    and NI-IMAQ will be appreciated.
    Thanks,
    Ravi.

    Hello Ravi,
    Thank you for using our discussion forums. We can extract the ROI by using the two IMAQ functions "IMAQ Select Rectangle" and "IMAQ Extract".  From there we can get the ROI coordinates using a property node from the extracted image.   Also, here are some examples regarding ROI manipulation that you might find helpful. 
    http://zone.ni.com/devzone/cda/epd/p/id/1239
    http://zone.ni.com/devzone/cda/tut/p/id/2887
    Regards,
    Vu D
    Applications Engineer

  • How to get rid of a background in an image?

    Does anyone know of an easy way to get rid of the background in the attached image and just keep the red print?
    Any ideas appreciated.
    If someone knows of an easy way, I have a much larger version of the image in PNG format.

    Another way to proceede is to convert it to B/W and adjust the conversion for taste. Then clean it up using curves or levels and clip it to a red fill layer. Here is a quick proof of concept. Doing it in sections would produce better  results.  The rectangles are new additions.
    I suspect this trade mark is still in force and owned by Honeywell and should not be used for commercial purposes.
    Paulo

  • How to get my photos printed with the full image?!

    I just bought iLife and when I select certain cropped photos to print, the top of someone's head gets cut off in the the photo. If I change sizes of prints or rotate the photo, it cuts off different amount of head but never gives the full image. I did not have this problem with iphoto before I installed this new version. I need to have access to printing photos. I use Canon MP500, ibook G4 and Airport Express for wireless printing. I think the prob is iLife cuz it didn't do this before in iPhoto and I have no prob with other applications. Help!!!!!!

    Select the photo you want to print, and click on Edit. Then click on Crop, and a drop-down menu will appear. Use this menu to select the photo size that you want to print. Then use the cropping frame to get the photo the way you want. It is important to select the correct size of the printed photo because the ratios of length to width are not the same from one size to another. For example, a 4 x 3 is closer in shape to a square than is a 5 x 7. You might have to try different photo sizes from the drop-down menu to get he result you want.

  • How to get X & Y co-ordinates from an image in labview

    Hello All,
    I have a captured waveform from an oscilloscope. From that image I want to find the X & Y co-ordinates. Can this happens using labview?
    For example, I want to calculate co-ordinates for the attached image (JPG format).
    I am using LabVIEW 2011. Your help will be appreciated
    Thanks & Regards,
    Manisha
    Solved!
    Go to Solution.
    Attachments:
    TEST WAVEFORM.JPG ‏143 KB

    It looks like you are acquiring data from a tektronix scope, the scope will be capable of giving you csv data than you having to interpret from an image. If you do need the xy co-ordinates, this may be a good starting point. http://zone.ni.com/devzone/cda/epd/p/id/2143
    Beginner? Try LabVIEW Basics
    Sharing bits of code? Try Snippets or LAVA Code Capture Tool
    Have you tried Quick Drop?, Visit QD Community.

  • How to get a particle emitter to have an image for color?

    There appears to be an option in the 'emitter' tab, under color mode, to change the color to 'take image color'. However, this option is not clickable for some reason. I am having a person cut a wall with a lightsaber and I want the emitter to not be a solid color. I will include a screenshot.

    From the Motion manual:
    "Take Image Color: When you choose this mode, each new particle’s color is based on the color of the image at the position where the particle was generated. This mode is available only when the Shape pop-up menu in the Emitter tab is set to Image."
    Andy

  • How to get rid of white edges surrounding png image file?

    hey im creating a website from scratch and when i drag my 8 bit png image file from my assets folder to my table on my page it apears to be fine, but when I check it in my browser there are white edges surrounding it which makes it look horrible because my background is not white. If anyone has any suggestions they'd be greatly appreciated. thanks

    file:///Users/sethmarx/Desktop/xmds%20site%20folder/master%20folder/web/web.html
    OK, now send me your computer. 
    We can't see files from your Local hard drive. Unless you publish your test page to a remote server space, nobody here can help you.  Sorry.
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    http://alt-web.com/
    http://twitter.com/altweb

Maybe you are looking for