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

Similar Messages

  • How to turn a black object into white on an image?

    Hi,
    on a picture. i can turn a blue object into yellow, green or any other color. and vice versa.
    To do that i know 5 different ways, or combination of those methods.
    1- Hue/Saturation
    2- Color Balance
    3- Selective Color
    4- Replece Color (Similar to Hue/Saturation)
    5- select the area, create a new layer, paint the selected area on new layer, blend the new layer with "linear burn".
    but when it comes to black, i can't change the black to another color with any of the ways above. So i was wondering if it is possible to turn a black object into white without killing the texture. Or cleaning the object from colors, making it colorless.
    best way i know so far is playing with "exposure" settings. but this time the objcet on the image is becoming blure and loosing its texture.
    Here is the object i m trying to make white (or colorless). Do you know any way to do it?
    i need to make that shoe as white/colorless as this one below.
    Thanks!

    Thanks for your help. But i wish it was that easy
    i can simply select the whole shoe and do ctrl+i (short cut to invert) to invert the dark colors to white. But while it turns the dark colors into white it also turns white parts into black. which i don't want to.
    it doesnt have to be plain white, i need it to be as white as possible then i can use it as a template to try different colors on it. (like the second photo i sent)
    If i do it with "invert" the when i paint it the shoe doesnt look real, its because with "invert" option, light parts becomming shadow, and shaddows becoming light.

  • 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

  • I want to know how to turn a word document into a jpeg so I can put the document on Facebook as a picture. I have made posters and if I do a print screen they are unable to be read, or if i turn it into a PDF there is no save as jpeg??

    I want to know how to turn a word document into a jpeg so I can put the document on Facebook as a picture. I have made posters and if I do a print screen they are unable to be read, or if i turn it into a PDF there is no save as jpeg??

    iOS device backups are stored in your iTunes library.
    Move your iTunes library to an external drive.

  • 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

  • How to convert a Graphics object into a JPG image?

    I have this simple question about how to make a Graphics object into a JPG file...
    I just need the names of the classes or the packages ... I'll figure out the rest of the details...
    Thanks...

    Anyway this might come in handy
    JPEGUtils.java
    ============
    * Created on Jun 22, 2005 by @author Tom Jacobs
    package tjacobs.jpeg;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.imageio.ImageIO;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageDecoder;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    * Utilities for saving JPEGs and GIFs
    public class JPEGUtils {
         private JPEGUtils() {
              super();
         public static void saveJPEG(BufferedImage thumbImage, File file, double compression) throws IOException {
              BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
              saveJPEG(thumbImage, out, compression);
              out.flush();
              out.close();
         public static void saveJPEG(BufferedImage thumbImage, OutputStream out, double compression) throws IOException {
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
              compression = Math.max(0, Math.min(compression, 100));
              param.setQuality((float)compression / 100.0f, false);
              encoder.setJPEGEncodeParam(param);
              encoder.encode(thumbImage);
         public static BufferedImage getJPEG(InputStream in) throws IOException {
              try {
                   JPEGImageDecoder decode = JPEGCodec.createJPEGDecoder(in);
                   BufferedImage im = decode.decodeAsBufferedImage();
                   return im;
              } finally {
                   in.close();
         public static BufferedImage getJPEG(File f) throws IOException {
              InputStream in = new BufferedInputStream(new FileInputStream(f));
              return getJPEG(in);
         public static void saveGif(RenderedImage image, File f) throws IOException {
              saveGif(image, new FileOutputStream(f));
         public static void saveGif(RenderedImage image, OutputStream out) throws IOException {
    //          Last time I checked, the J2SE 1.4.2 shipped with readers for gif, jpeg and png, but writers only for jpeg and png. If you haven't downloaded the whole JAI, and you want a writer for gif (as well as readers and writers for several other formats) download:
    //          http://java.sun.com/products/java-media/jai/downloads/download-iio.html
              ImageIO.write(image, "gif", out);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
    }

  • How to add a ChartOfAccounts object into the database.

    how to add a ChartOfAccounts object into the database. please shows sample code
    thanks

    Dim CoA As SAPbobsCOM.ChartOfAccounts
                CoA = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oChartOfAccounts)
                CoA.Code = 11223344
                CoA.ExternalCode = "a1234"
                CoA.ForeignName = "f Test Account"
                CoA.Name = "Test Account"
                CoA.AccountType = SAPbobsCOM.BoAccountTypes.at_Other
                CoA.ActiveAccount = SAPbobsCOM.BoYesNoEnum.tYES
                CoA.FatherAccountKey = 100001
                If CoA.Add <> 0 Then
                    MessageBox.Show(oCompany.GetLastErrorDescription)
                Else
                    MessageBox.Show("Added Account")
                End If
    Remember the father account key must be a valid account number in the company where you are trying to add the new account.  (The G/L Account code seen in the SBO client)

  • How to turn a pdf file into excel document and keep original format

    I Have an excel bid form that i use all the time ,then i convert it into a PDF  And once in a while i need to add something to it  I paid for acrobat but when i try to turn the PDF back into an excel document the format is changed , the columns are in the wrong places And it does not look at all like the original excell form is there any thing i can do to  fix this If not this will be useless to me  any help appreciated

    A PDF does not contain any spreadsheet, word processing or page layout file format information.
    No "format", columns, rows, etc.
    "When you create a PDF, you’re painting a picture. Your paintbrush is the is the result of a combination of the software used to create the source document and the software you’ve chosen to convert your source document into the universal electronic document format we all know as PDF.
    Like the painter’s brushstrokes, each character, each line and each image is fundamentally independent, but they can interact with each other to produce particular visual effects. On the PDF page, objects are connected by a coordinate system and not a lot else. There’s no logical, semantic connection between the letters comprising a word; characters simply happen at a series of locations on the rendered page.
    As originally designed, PDF is fundamentally a system for painting objects onto a page, plus a whole lot of other features we aren’t talking about right now! There’s no innate concept of words, sentences, paragraphs, columns, headings, images, tables, lists, footnotes – any of the semantic structures that distinguish a “document” from a meaningless heap of letters, shapes and colors. PDF is fundamentally about how the document appears on the page, not how it looks when abstracted from the page."
    Duff Johnson, Each PDF Page Is a Painting
    http://talkingpdf.org/each-pdf-page-is-a-painting/ 
    Be well...

  • How do I convert an Object into an Array?

    If I have an instance of type object that I know is really a DataGrid row that was cast into an object when passed to a function, how can I cast that Object to an array, such that each index of this array would correspond to the information in a given column of the row?

    @Sathyamoorthi
    Can you please explain what this function does? Essentially, what should be contained in the String?
    I printed out the string and it seems like I am getting a random row in the Object, as opposed to first or last. Why is that?
    UPDATE: I printed out the value of dataGrid0.columns[5].dataField but it just turned out to be the id of the column.

  • How to turn an animated .gif into a hyperlink

    Hey everyone,
    Im new to the forums and dreamweaver. I created an animated .gif file in photoshop that i want to use as an advertisement banner on a website. Now that the banner is created (on photoshop), I would like to turn the whole image into a link so that when someone clicks on it, it will redirect them to another website. How do I do this in dreamweaver??
    Any help is greatly appreciated!

    is JQ iweb compatible?
    jQuery is a very popular JavaScript library with which you can bring interactivity into web pages.  I know almost nothing about iWeb except that it is consumer level software for non-coders.  That said, if you can access the source code (HTML and CSS), you should be able to use jQuery plug-ins in your web pages.
    jQuery Cycle Plug-in (click on examples, view source in browser to see the code).
    http://jquery.malsup.com/cycle/
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    http://alt-web.com/
    http://twitter.com/altweb

  • How to turn my macbook pro into router via a usb dongle

    hello guys,,,
    would you please help me in this matter,,,
    how could i to turn my macbook pro into router via a usb dongle, in order for my other apple products can have internet connection too.
    im connected to the web via vodafone usb dongle.
    thank you!

    System Preferences>Sharing>Internet Sharing. Your MBP needs to be on all the time and not sleeping.

  • How to pass a locale object into another function?

    Greetings,
    i like to pass a locale object into another function. These are my code below
    import java.util.*;
    public class Locales{
         public static void main(String[] args){
              Locale locale= new Locale("EN", "US");
              convert(locale);
    public void convert(Locale convert)
         String language = convert.getDisplayLanguage();
         System.out.println(language);          
    }I got this error:
    Locales.java:6: non-static method convert(java.util.Locale) cannot be referenced from a static content
                    convert(locale);
                    ^How do i correct it?
    Thanks

    Did you bother to do a search?
    Did you bother to read any of the material that the search would have linked you to?
    If you had then you would be able to understand where you are going wrong and how to fix it yourself. Instead of being spoonfed by us.

  • How to turn an old laptop into a jukebox

    hi all!
    because this is my first post, i just want to say that i really like the arch community. didn't need to post anything until now, but since i switched to arch (2-3 years ago), this forum & wiki always helped me. so thanks!
    ok - i want to turn an olld laptop into a jukebox for partys. it is an acer aspire 1692 (Pentium-M 740 1.73GHz, 512MB RAM, 80GB HDD, ATI Mobility Radeon X700 64MB). so what i want is nothing than a fast system, playing the music. the music player should have the following (very basic) features: shuffle, fading, queuing, music library and fastness. my current music library contains around 19000 songs (~100gb). i think i would like to use openbox. but i still can't find a music player. i really like mpd but there is no such feature like queuing (for example, having a playlist, and then adding a song as the next song to be played in the cue, and then continue with the playlist).
    any suggestions? comments?
    thanks!
    hooch

    I would like to see you fit 100GB worth of music into an 80GB HDD ;P
    Are you saying none of those https://wiki.archlinux.org/index.php/Co … ions#Audio fits your needs?
    I would pause mplayer playing the playlist and open another one to play just this track, then return to the first one and continue with the playlist :-) I don't think mplayer supports fast handling of music libraries of ~100GB-size though. How about http://www.clementine-player.org/ ?
    Last edited by karol (2010-12-15 15:35:15)

  • How to get customer-specific objects into PCUI ?

    Hello,
    we want to get an Z-table as tab page of the business partner-application into PCUI. It should 'only' be possible to create new entries - today there is no need to modify or delete records.
    Does there exist something like a "cookbook" on this task or has anyone of you experience how to get customer-specific objects (without using EEWB) into PCUI ?
    Thanks in advance
    Martin

    Option 1:
    If you are good in ABAP.
    You can add new tab in which create a new Field group. Assign it to a model access clas in which handle the table update.You can get the details in PCUI cookbook itsel.
    Option 2:
    If you are good at java
    Develop an FM to update the table.
    Call the FM from webdynpro
    Include this webdynpro as HTML viewer in PCUI.
    Regards,
    Abdul Raheem S

  • How do u pass an object into a method

    I want to create a method getData that takes an object of type Helper and returns an object of the same type.
    how do u pass objects into a method and how do u get objects as returns im a bit confused

    That will just allow you to pass a parameter. If you want to return a helper object
    Helper paramHelper = new Helper();
    Helper someHelper = callMethod(paramHelper);
    public Helper callMethod(Helper hobj) {
        //<some code>
        Helper retHelper = new Helper();
        //<blah, blah>
        return retHelper;

Maybe you are looking for

  • How do I stop Lion intercepting Control Down in Excel

    Control Up works but Lion grabs left,right, and down. Is there someway to make Lion ignore these when working in excel?

  • Adding a button to each row of a tabular form

    Hi, I'm new to APEX. I've searched the forums high and low for a couple days, but no go on a solution to my problem. Perhaps I'm not phrasing my search right. I have a tabular form. The columns in each row save to a table called STORE. At the end of

  • Employee number is mandatory at item level

    Dear experts I want employee nuber mandatory at item level at the time of saving order , pls give me ur suggestion while customising incomplition log.  pls help me out Regards vikas

  • Function in to_date format...

    Hi I have one function which retun value in mm/dd/yyyy format. inside select clause iwant compare this function with mm/yyyy format. but function can not come with to_date format. need help to work wround due to this select query out put getting gene

  • Making Polling Interval on DB Adapter as a property.

    Hi All, I am trying to make the polling interval on my db adapter as a prpoerty so the polling interval time gets read from a property file and hence i dont have to redploy the process when i want to change the polling time interval. Is it possible ?