How can I make a BufferedImage out of packed and non-packed int pixels?

Hi all,
I'm trying to turn a byte array of pixels into an int array, then into a buffered Image. In addition to the pixels, I've also got the color (and alpha) masks, width, height, and bit depth of the image. My problem is that the bits per pixel can change, the individual bytes cannot contain the pixels, and many times an int is not fully utilized to store an entire pixel (16bit pixels, for example). When I attempt to create a WritableRaster with a DataBufferInt, I get errors that I don't get if I re-package the 16bit pixels in a short[], (using DataBufferUShort). I don't want to have to do this, since it means reprocessing the entire array yet another time. One last thing. I've already got a working method for "up-converting" the int[] to 32bit pixels, though I'd love to see somebody else's attempt at this if they'd like to share. Mostly, I'm just looking for a way to use the data I have to create a BufferedImage that preserves the data type of the data. Here's some of the code I'm using now. (The byte array may contain MIPmaps, so that's the reason for the imgIndex...)
<edit> Sorry, I also don't want to have to use the switch (or if...else) statements. I'm looking for a way to use the info I have to write one piece of code that will work for all the data types...</edit>
private static int[] get8888(byte[] pixels, int format, int width, int height, int imgIndex) {
   int[] pixels8888 = new int[width * height / (int)Math.pow(4, imgIndex)];
   int offset = 0;
   for(int i = 0; i < imgIndex; i++) {
      offset += (width * height) / (int)Math.pow(4, i);
   switch(format) {
      case TYPE_A8R8G8B8:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = (pixels[(i + offset) * 4] & 0xff) | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | (pixels[(i + offset) * 4 + 3] & 0xff) << 24;
         break;
      case TYPE_A1R5G5B5:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = pixels[(i + offset) * 2] & 0xff | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
            int a = ( ( (pixels8888[i] & 0x8000) >>> 15 ) == 1 ) ? 0xFF : 0;
            int r = (pixels8888[i] & 0x7c00) >>> 7;
            int g = (pixels8888[i] & 0x3e0) >>> 2;
            int b = (pixels8888[i] & 0x1f) << 3;
            pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
         break;
      case TYPE_A4R4G4B4:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
            int a = (pixels8888[i] & 0xf000) >>> 12;
            int r = (pixels8888[i] & 0xf00) >>> 8;
            int g = (pixels8888[i] & 0xf0) >>> 4;
            int b = (pixels8888[i] & 0xf);
            a = a | (a << 4);
            r = r | (r << 4);
            g = g | (g << 4);
            b = b | (b << 4);
            pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
         break;
      case TYPE_A8R3G3B2:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
            int a = (pixels8888[i] & 0xff00) >>> 8;
            int r = (pixels8888[i] & 0xe0);
            int g = (pixels8888[i] & 0x1c) << 3;
            int b = (pixels8888[i] & 0x3) << 6;
            pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
         break;
      case TYPE_R8G8B8:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = (pixels[(i + offset) * 3] & 0xff) | (pixels[(i + offset) * 3 + 1] & 0xff) << 8 | (pixels[(i + offset) * 3 + 2] & 0xff) << 16 | 0xff000000;
         break;
      case TYPE_R5G6B5:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
            int a = 0xFF;
            int r = (pixels8888[i] & 0xf800) >>> 8;
            int g = (pixels8888[i] & 0x7e0) >>> 3;
            int b = (pixels8888[i] & 0x1f) << 3;
            pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
         break;
      case TYPE_R3G3B2:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = pixels[(i + offset)];
            int a = 0xFF;
            int r = (pixels8888[i] & 0xe0);
            int g = (pixels8888[i] & 0x1c) << 3;
            int b = (pixels8888[i] & 0x3) << 6;
            pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
         break;
      case TYPE_X8R8G8B8:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = (pixels[(i + offset) * 4]) & 0xff | (pixels[(i + offset) * 4 + 1] & 0xff) << 8 | (pixels[(i + offset) * 4 + 2] & 0xff) << 16 | 0xff000000;
         break;
      case TYPE_X1R5G5B5:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = (pixels[(i + offset) * 2] & 0xff) | (pixels[(i + offset) * 2 + 1] & 0xff) << 8;
            int a = 0xff;
            int r = (pixels8888[i] & 0x7c00) >>> 7;
            int g = (pixels8888[i] & 0x3e0) >>> 2;
            int b = (pixels8888[i] & 0x1f) << 3;
            pixels8888[i] = a << 24 | r << 16 | g << 8 | b;  
         break;
      case TYPE_X4R4G4B4:
         for(int i = 0; i < pixels8888.length; i++) {
            pixels8888[i] = pixels[(i + offset) * 2] | (pixels[(i + offset) * 2 + 1] << 8);
            int r = (pixels8888[i] & 0xf00) >>> 8;
            int g = (pixels8888[i] & 0xf0) >>> 4;
            int b = (pixels8888[i] & 0xf);
            r = r | (r << 4);
            g = g | (g << 4);
            b = b | (b << 4);
            pixels8888[i] = 0xff << 24 | r << 16 | g << 8 | b;  
         break;
      default:
         System.out.println("File type not recognized");
   return pixels8888;
}After I've done this, I can just create a DataBufferInt with the returned pixel array and generate the bufferedImage. I'm doing this currently, but I'd like to be able to write code that would take the image type and return a matching BufferedImage, (of type TYPE_USHORT_565 for example). Any hints?
Edited by: Quasi_Stomach on Jul 31, 2009 12:33 PM

i figured it out myself !!!

Similar Messages

  • How can I make a fade out effect at the end of the song in garageband for iPad?

    I want to made this effect but honestly I have no idea about what I have to do. u.u Please help.

    ClaudioWalrus wrote:
    How can I make a fade out effect at the end of the song in garageband for iPad?
    GB for iPad doesn't have volume automation, you'd need to import the project into GB on a Mac to create the fade with a volume curve.
    as an alt, finish your song and export the audio file, then import the audio file in an audio editor and create a volume fade with that:
    http://www.bulletsandbones.com/GB/GBFAQ.html#audioeditors
    (Let the page FULLY load. The link to your answer is at the top of your screen)

  • How can I make the playback buttons of YouTube and other plug-ins bigger since they are so tiny?

    How can I make the playback buttons of YouTube and other plug-ins bigger since they are so tiny in Firefox? I tried some suggestions that dealt with entering "about:config" in a fresh browser, but to no avail. I also downloaded an add-on called "Theme Font & Size Changer", but that didn't work either. So, I am reaching out here as that was a suggestion that another user here offered.

    Ah, yes- that is an ultra high DPI (dots per inch) display. This is a known issue in Flash Player, which Adobe is working on fixing.
    In the mean time, you can get some videos to have normal-sized controls by switching Youtube to the HTML5 video player:
    In Firefox, go to https://www.youtube.com/html5 and click the "Request the HTML5 player" button.

  • Help - I have an apple id account, where is my iPod and iPad registered, but also the iPod of my daughter. How can I make an account for my daughter and keep all the apps she has on her iPod?

    Help - I have an apple id account, where is my iPod and iPad registered, but also the iPod of my daughter. How can I make an account for my daughter and keep all the apps she has on her iPod and in her own iTunes?

    Sorry, content bought with one Apple ID cannot be merged or transferred to another Apple ID.

  • How can  I get rejected photos out of LR5 and off the HD?

    When I try to deleted rejected photos in LR5 on my iMac, I get a dialog saying they can't be sent to the trash.  How can I get unwanted photos out of LR5 and off the hard drive?

    Instead of hitting just the delete key, you need to hit ⌘+Del and one of the choices will be to remove from hard drive.

  • How can I make the popup with empty fileds and create new record?

    I would like to use a popup to create new record.
    I created a af:popup by drag and drop a VO from data control to jsff. then, I created a button and place a af:showPopupBehavior. I was able to popup window by click the button.
    however, the window filled with the information from the 1st record. and when I select a record in table and click popup, the popup is filled with that record.
    How can I make the popup with empty fileds and create new record by saving the popup?
    Thanks

    You can have edit and new buttons, in the PopupFetchEvent identify button source (using popupFetchEvent.getLaunchSourceClientId()) if new button clicked clear the binding using below code.
    If you want to see empty fields, in the popup PopupFetchEvent clear the input component bindings.
    resetBindingValue("#{bindings.<componentid>.inputValue}", null);
        public static void resetBindingValue(String expression, Object newValue) {
            FacesContext ctx = FacesContext.getCurrentInstance();
            Application app = ctx.getApplication();
            ExpressionFactory elFactory = app.getExpressionFactory();
            ELContext elContext = ctx.getELContext();
            ValueExpression valueExp = elFactory.createValueExpression(elContext,expression,Object.class);
            Class bindClass = valueExp.getType(elContext);
            valueExp.setValue(elContext,newValue);
        }

  • I want to remove my itunes library to a thumb make memory space - how can I make sure I keep all playlists and organizing intact?

    I want to remove my itunes library to a thumb make memory space - how can I make sure I keep all playlists and organizing intact?

    Do you mean a flash drive?  I don't know if I would trust one of those entirely.  Make sure you make a backup.
    Copy the entire iTunes folder to the flash drive.  Start iTunes while holding down the option/alt key and guide it to the library on the flash drive.  If you forget to plug in the flash drive before starting iTunes in the future you will have to do the option start thing again.

  • We had to change the feed adress and the epsiode adresses. Now all the episodes of my podcast are downloaded (although i have downloaded them already). How can I make the changes in my feed and avoid that all the episodes are reloaded?

    Hello,
    We had to change the feed adress (<itunes:new-feed-url>)and the epsiode adresses in the feed because the feed and the episode-files are on a new server. Now when i open my iTunes subscription of our podcast all the episodes of my podcast are downloaded again (although i have downloaded them already).
    My Question therefore is: How can I make the changes in my feed and avoid that all the episodes are reloaded?
    Maybe have an answer?
    Thank you very much.

    Thank you very much for your answer
    As I see now, our 'guid' tags contain the episode URLs
    To avoid this problem in the future i would like to change guid tags. Can you please tell me how a guid tag should look like if it is not the URL?
    Thank you for helping us!
    ps now it looks like this eg:
    <guid isPermaLink="false">http://www.castyourart.com/podcasts/213_thinkglobal_en.mp4</guid>

  • How can i make a the out put in bold letters

    let say that this code output is public String toTitle(){
              return "Title: " + titleBook;
         }Title: Spectacular Chemical Experiments
    Title: Terror
    now how can I make just title bold like this
    Title: Spectacular Chemical Experiments
    Title: Terror
    thanks

    If your job and life depends on it, many consoles support ANSI escape characters; the problem is that they are ignored from System.out.
    It can be done with JNI:
    http://www.rgagnon.com/javadetails/java-0469.html
    on linux, the command would be "echo -e"
    Again, I say this if your job and life depends on it. It ain't pretty. (well, the colors are maybe; the code isn't.)

  • How can i make a connection between an application and a database over net

    dear sir
    how can i make connection between an appliction and a database over internet while the client side appliction is behind proxy and firewall
    for example how the live update of norton antivirus makes connection to the data server to make comparetions and get new virus definitions
    does that depend on sockets technology ?
    what references can guide me to the solution please?

    The ability to do so depends entirely on the JDBC driver implementation having some proxy method. It needs to recognize the HTTP or SOCKS proxy and use them to connect, and the firewall and proxy need to allow those specific port connections.
    To the best of my knowledge, all of these update utilities, e.g. live update for Netscape, Norton, etc., do not connect directly to the database. As it is, no sane security person would allow a database to be exposed to the Net. Rather, they connect using HTTP or HTTPS, which normally traverses firewalls just fine, to connect to a Web or application server on the far end. That application server then parses the request and retrieves whatever it needs to from the database.
    In other words, you cannot have a 2-tier client/server application. You need a 3-tier application:
    your client -> Web/app server -> database
    where the connection from your client to the Web/app server is over http or https through the firewall and proxies.
    Hope this helps.
    Avi
    dear sir
    how can i make connection between an appliction and a
    database over internet while the client side
    appliction is behind proxy and firewall
    for example how the live update of norton antivirus
    makes connection to the data server to make
    comparetions and get new virus definitions
    does that depend on sockets technology ?
    what references can guide me to the solution please?

  • How can i make cotrol file which have conveyor and ?

    how can i make cotrol file which have conveyor " to move the bottle and slider " to fill the same bottle ?
    i attach my control file.............
    " Science is came....not come "
    I study Mechatronics Engineer
    skype : t_alhowaiti
    Attachments:
    convyer.ctl ‏16 KB

    Jeff·Þ·Bohrer wrote:
    billko wrote:
    ThaerAL-Hwaiti wrote:
    i want to make a production line which move a bottle on a conveyor and fill it .
    That's all good and fine, but what have you tried codewise?  Let's see what you have so far and we can go from there.
    The easy answer is "an assignment" and a desire to pass the course without actually needing to read and comprehend information.
    I as trying to be diplomatic about it. 
    Bill
    (Mid-Level minion.)
    My support system ensures that I don't look totally incompetent.
    Proud to say that I've progressed beyond knowing just enough to be dangerous. I now know enough to know that I have no clue about anything at all.

  • How can I make my Outlook sync with ical and address book on more than one mac?

    It currently syncs with my iMac through 'this computer' folder, but i dont have outlook on my macbook, so basically... how can i make my outlook automatically convert/sync to icloud enabled folders?
    Not too confusing i hope.

    Outlook won't work with iCloud. On your Mac.

  • I want to create a playlist on an old iPod Nano (I think it's from the second generation), but the computer it was originally linked to via iTunes died years ago.  How can I make a playlist out of existing songs on the iPod?

    Hello there,
    I have an old iPod nano which I think is from the second generation (model number A1199 if that helps) with software at the latest version it can accept, 1.1.3.  I wish to make a playlist out of the songs currently on the iPod, but I can't see any easy way to do that from the iPod itself.  The next logical thought is to do it through iTunes, but the iTunes that was originally synced to the iPod died several years ago now, so I can't access that to make a playlist through (it's a very old iPod).  I do have iTunes currently on this computer, but that's synced with my iPhone and stores different songs which I don't want to be mixed with those from the old iPod (due to the mostly nostalgic nature of the iPod songs).  Is there any way I can either create a new playlist from the iPod itself, or through iTunes without having to sync?  Also note that most of the songs on the old iPod were uploaded to iTunes from CDs and so aren't connected with any iTunes Login.
    Thanks for any help you can give.  Also, I sorta need to create this playlist ASAP so any advice you could give would be much appreciated
    ~Imamadmad

    The old iTunes library was lost with the old PC.  However, it all that music and content is still on your iPod there are many ways you can extract this content from the iPod and import it back into iTunes.
    Your iPod is designed to sync with only one iTunes library at a time.  It will recognize the iTunes library on the new PC as a new library.  If you sync the iPod with this new library, all content will be erased from the iPod and replaced with what is in the new library.  So what you will want to do is copy everything from the iPod to your new iTunes library on your PC first.
    See this older post from another forum member Zevoneer covering the different methods and software available to assist you with the task of copying content from your iPod back to your PC and into iTunes.
    https://discussions.apple.com/thread/2452022?start=0&tstart=0
    B-rock

  • How can we make consecutive left outer joins in Composite Provider?

    Hi,
    For the following design:
    Sales order and Delivery DSO's are unions on field Delivery Number.
    Invoice(Billing DSO) is having left outer join and joins with Sales Order DSO's based on the field Sales Order Number.
    Shipment DSO has left outer join, joins with Invoice DSO based on Delivery number.
    My doubt here in this composite provider design, is more than one consecutive left outer joins(in Invoice, shipment dso join) are allowed?
    Since this is possible in SAP ERP through writing abap codes, I came across that this kind of modelling is not possible in BW on  Hana through Composite provide kindly suggest how can we achieve this design in SAP BW On hana.
    Regards,
    Antony Jerald.

    Hi,
    Could anyone please help me on this?
    Hope, you are able to understand my question.  Please suggest.
    Regards,
    Antony Jerald.

  • How can I make ANY vector  graphics with graphics2D and save on clipboard?

    I am at my wits end here, and need some help. Simply put, I have a program that creates a basic x-y graph, drawn in a jpanel. I want to create the graph as a vector (emf, eps, svg, I don't care anymore, any of them would be good). But, all I get is a jpg or bitmap.
    I tried using the infamous FreeHEP programs, but it won't recognize the output as anything but "image" which means bitmap/jpg.
         The user enters x/y data, clicks a button, which crreates a jpanel thusly:
    public class GraphMaker extends JPanel {
    static BufferedImage image = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    GraphMaker(double[] xVals, double[] yVals, double[] sems){
    setPreferredSize(new Dimension (600,500));     
    symSize = 10;
    XminV = 0;
    XmaxV = 0;
    // code here just converts input x and y's to pixel coordinates, spacing of ticks, etc...
    for (int i =0;i < ArLn; i++){
    gX[i] = xO + (gX[i] * xRat);
    gX[i] -= xStart;
    gY[i] = gY[i] * yRat;
    gY[i] = yEnd - gY;
    semVal[i] = semVal[i]*yRat;
         Ymin = yEnd - (Ymin*yRat);
         Ymax = yEnd - (Ymax*yRat);
    BufferedImage anImage = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = anImage.createGraphics();
    g2.setBackground(white);
    g2.setColor( Color.WHITE );
    g2.fillRect(0,0,600,500);
    g2.setStroke(stroke);
    // here I use the values to draw lines and circles - nothing spectacular:
              g2.setPaint(Color.blue);
              int ii = 0;
              for ( int j = 0; j < ArLn[ii]; j++ ) {
    g2.fill(new Ellipse2D.Float(LgX[ii][j] - symOffst, gY[ii][j]-symOffst, symSize,symSize));
    g2.draw(new Line2D.Float(LgX[ii][j],(gY[ii][j]-semVal[ii][j]),LgX[ii][j],(gY[ii][j]+semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]-semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]-semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]+semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]+semVal[ii][j])));
                        g2.draw(new Line2D.Float(xLoVal[ii],yLoVal[ii],xHiVal[ii],yHiVal[ii]));
    image = anImage;
    And, when the user clicks on the "copy" button, invokes this:
    public class Freep implements Transferable, ClipboardOwner {
         public static final DataFlavor POSTSCRIPT_FLAVOR = new DataFlavor("application/postscript", "Postscript");
         private static DataFlavor[] supportedFlavors = {
              DataFlavor.imageFlavor,
              POSTSCRIPT_FLAVOR,
              DataFlavor.stringFlavor
         private static JPanel chart;
         private int width;
         private int height;
         public Freep(JPanel theGraph, int width, int height) {
              this.theGraph = Graphs;
              this.width = width;
              this.height = height;
    //******This is the key method right here: It is ALWAYS imageFlavor, never anything else. How do I make this an EPS flavor?
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (flavor.equals(DataFlavor.imageFlavor)) {
    return GraphMaker.image;
    else if (flavor.equals(POSTSCRIPT_FLAVOR)) {
                   return new ByteArrayInputStream(epsOutputStream().toByteArray());
    else if (flavor.equals(DataFlavor.stringFlavor)) {
                   return epsOutputStream().toString();
              } else{
                   throw new UnsupportedFlavorException(flavor);
         private ByteArrayOutputStream epsOutputStream() throws IOException {
    EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
         public DataFlavor[] getTransferDataFlavors() {
              return supportedFlavors;
         public boolean isDataFlavorSupported(DataFlavor flavor) {
              for(DataFlavor f : supportedFlavors) {
                   if (f.equals(flavor))
                        return true;
              return false;
         public void lostOwnership(Clipboard arg, Transferable arg1) {
    The same happens with FreeHEP - I want the flavor to be EMF, but the program sees an image so it is always imageFlavor. I know I am missing something, but what, I don't know.
    thanks for your help.

    I don't think there's a built-in solution. One workaround I've seen is to create a dummy graphics class that overrides the desired drawing functions. Instead of actually drawing pixels, the object writes postscript commands to a buffer. There also seems to be commercial code that does exactly this.

Maybe you are looking for

  • Max # line items in a purchase order

    What is the maximun number of line items that can be created in a purchase order or in a contract? Thanks

  • Model View Control

    Hi.. i need some help when designing the view part of my application. My main problem is that sometimes i do not know how to separate the control code from the one needed in the view part.For example, if I have some componentes(implementes mouse moti

  • Really Weird Problem, IDK How to Fix

    So just this morning i pulled out my MacBook like every morning to see whats up on the internet when for reason my computer starting having this little black box around whatever im active in. like right now its around the yellow - to minimize firefox

  • "Improved" iTunes 9  still crasheds/won't load

    I downloaded itunes 9 when it first came out and it crashed every time, so I dumped it and went back to version 8. I downloaded the "fix" and it still crashes. I have yet to see what the new version looks like, much less what it does. I'm running OS1

  • Event title wiped out and replaced w 'New Event'

    when I add an event to iCal and type in the subject, I add it to my calendar... (synced via iCloud) and then when I go back to view the calendar, the actual text typed into the subject line is gone and only 'New Event' shows up. I have to think it ha