BufferedImage to ByteBuffer ?

I have an applications that I am using Robot to do screen capture. The server that I am going to be connecting to from my Java app has a class that can accept org.apache.mina.common.ByteBuffer data. That data will then be encoded and create a video stream.
Is it possible to convert the BufferedImage into a ByteBuffer ?
The class that accepts the ByteBuffer has a method called addData(org.apache.mina.common.ByteBuffer); I am hoping that this is as simple as converting my BufferedImage into a ByteBuffer :)
Thanks for any suggestions or help on this.
-Matthew

Does this place have a label like "Apache Support Board"?
I can only assume that a ByteBuffer would accept bytes, so using ImageIO and a ByteArrayOutputStream could help you.

Similar Messages

  • ByteBuffer to BufferedImage over WritableRaster: Image is upside down

    Hey all!
    I have a native Buffer containing RGB-Values (3 bytes per Pixel). I found a Code-Sample in this Forum which works fine for me:
    [http://forums.sun.com/thread.jspa?messageID=10784665#10784665]
    The thing is, the BufferedImage is "Upside down". Is there a simple way to tell the Raster (or whatever) in which direction the buffer should be read?
    I don't wan't to use image transformation because of the time needed by CPU for the transformation.
    Best regards,
    Billie

    The BufferedImage is stored in a File (JPEG).
    The callback-Function is called from JNI and the ByteBuffer contains the RGB value's. This code creates my BufferedImage:
        private ByteBuffer buffer = null;
        private int[] bOffs = { 0, 1, 2 };
        private ColorModel colorModel =
            new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
                new int[] { 8, 8, 8 },
                false,
                false,
                Transparency.TRANSLUCENT,
                DataBuffer.TYPE_BYTE);
         * Called within JNI
         * @param byteBuffer the native memory buffer
         * @param width the image with in pixels
         * @param height the image height in pixels
         * @param bitCount the number of bits per pixel
        protected synchronized void callback(ByteBuffer byteBuffer, int width, int height, int bitCount) {
            String method = "callback(ByteBuffer, int, int, int)";
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(method, "byteBuffer="
                    + byteBuffer
                    + ",width="
                    + width
                    + ",height="
                    + height
                    + ",bitCount="
                    + bitCount);
            try {
                if (buffer == null) {
                    buffer = ByteBuffer.allocate(byteBuffer.capacity());
                buffer.position(0);
                buffer.put(byteBuffer);
                WritableRaster raster =
                    Raster.createInterleavedRaster(new DataBufferByte(buffer.array(), buffer.capacity()),
                        width,
                        height,
                        width * 3,
                        3,
                        bOffs,
                        null);
                bfImage = new BufferedImage(colorModel, raster, false, null);
            } catch (Exception e) {
                LOGGER.error(method, "Error createing BufferedImage", e);
            notify();
        }And this code stores the image on disk:
            ImageWriterSpi imageWriterSpi = (ImageWriterSpi) IIORegistry
                .getDefaultInstance()
                .getServiceProviderByClass(Class.forName(properties.getProperty(KEY_IMAGE_SPI))); // com.sun.imageio.plugins.jpeg.JPEGImageWriterSpi
            imageWriter = imageWriterSpi.createWriterInstance();
                        imageWriter.reset();
                        imageWriter.setOutput(ImageIO.createImageOutputStream(new FileOutputStream(new File(
                            directory,
                            fileName + ".jpg"))));
                        imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);The BufferedImage isn't touched between this two parts.

  • To obtain BufferedImage from Scene 3D

    Hi all!!! I want to obtain snapshots from Scene 3D to do a video with JMF (Java Media Framework). How I do it??
    Regards!

    // read the buffer to byteBuffer
                GL11.glReadBuffer(GL11.GL_FRONT);
                ByteBuffer pixels = ByteBuffer.allocateDirect(400*400*4);
                GL11.glReadPixels(0, 0, 400, 400, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pixels);
                ColorModel glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
                                                new int[] {8,8,8,0},
                                                false,
                                                false,
                                                ComponentColorModel.OPAQUE,
                                                DataBuffer.TYPE_BYTE);
                int[] bitMasks = new int[] {8,8,8,0};
                int[] band = new int[3];
                // again, what is this?
                SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, 400, 400,bitMasks);
                // make array from byteBuffer to make a DataBufferByte from array...
                byte [] byteA=new byte[400*400*3];
                System.out.println(byteA.length);
                pixels.get(byteA);
                DataBuffer db = new DataBufferByte(byteA, 400*400*3, 0);
                //make my raster
                WritableRaster raster = Raster.createInterleavedRaster(db, 400, 400, 400*3, 3, band, null);
                // make my image
                BufferedImage image = new BufferedImage(glColorModel, raster, false, null);//new java.util.Hashtable());the above produces an image! yey! it is however grayscale, can anybody help?
    Edited by: IJustWantToSayHelloWorld on Aug 5, 2009 4:12 AM

  • Forming an image from a ByteBuffer

    I would be grateful if anybody could help me with a problem i am having with my program, i am trying to read pixels to form an image, i have the whole thing working now, however it is grayscale, and i cant work out why. Any help would be appreciated.
         GL11.glReadBuffer(GL11.GL_FRONT);
                ByteBuffer pixels = ByteBuffer.allocateDirect(400*400*3);
                GL11.glReadPixels(0, 0, 400, 400, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pixels);
                ColorModel glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
                                                new int[] {8,8,8,0},
                                                false,
                                                false,
                                                ComponentColorModel.OPAQUE,
                                                DataBuffer.TYPE_BYTE);
                int[] band = new int[3];
                // make array from byteBuffer to make a DataBufferByte from array...
                byte [] byteA=new byte[400*400*3];
                pixels.get(byteA);
                DataBuffer db = new DataBufferByte(byteA, 400*400*3, 0);
                WritableRaster raster = Raster.createInterleavedRaster(db, 400, 400, 400*3, 3, band, null);
                // make my image
                BufferedImage image = new BufferedImage(glColorModel, raster, false, null);//new java.util.Hashtable());thanks

    Ok, investigation further:
                for (int i = 0; i < 1600 ; i ++){
                    System.out.println(byteA);
    }produces non grayscale numbers, such as 76 51 25 76 51 25 76 51 25 , ie the background. This means the problem is in the raster part, maybe the glColorModel? the thing is i just coppied the glColorModel straight from my texture loading thing, and they are in colour....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • BufferedImage creation slow in JDK 1.4.2

    Hi,
    The creation of BufferedImage of size 400x400 takes 156ms in JDK1.4.2. It used to take less than 10ms in JDK1.3.1.
    Image image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_ARGB);
    In JDK1.4.2, for sizes 363x363 and above, it takes 156ms and
    for sizes under 363x363, it takes close to 0ms.
    Is this a bug in JDK 1.4.2? I noticed similar behavior in JDK1.5 also.
    My machine configuration:
    Windows XP, 512MB Ram, 1.7GHz
    Thanks,
    Bindu

    The arg type of the setter and the return type of the getter must match up or you'll get this exception.

  • Image processing with BLOBS: how to write BufferedImage to a BLOB

    Hi everybody - thanks in advance for any input on that topic.
    I'm doing image processing using AWT and 2D. Images are stored in a RDBMS as BLOB Type, which I get using JDBC and convert to a BufferedImage using a JDBCImageDecoder.
    Now, I have my BufferedImage and I can process them using the appropriate filters (ConvolveOp e.g.)
    Writing the BufferedImages to disk or display on screen is easy. But I can't get to write them to a BLOB Object. Any Hint ?
    (Of course, I'm speaking of oracle.sql.BLOB objects, not java.sql.Blob).
    Thanks and have a nice day

    Billy,
    Thank you for your answer. I have two questions.
    First what that means "Bob's your uncle ?" I'm a french man, not used to english special sentences ou jargon. Would enjoy to know !
    Second, I have created a PL/SQL procedure to update my table. I face a problem.
    I want to initialize b_lob with the img_blob value but I get an error : "ORA-22922: nonexistent LOB value". WHere do my error comes from ? I am fairly new in this stuff of BLOB.
    Below my procedure.
    Thank for your kind help.
    Christian.
    create or replace
    procedure insert_img as
    f_lob bfile;
    b_lob blob;
    loops number default 0 ;
    lines number default 0;
    stmt varchar2(4000);
    cursor c1 is select img_blob, file_name, pk from photos FOR UPDATE ;
    begin
    NULL;
    dbms_output.enable(900000);
    stmt := 'SELECT COUNT(*) FROM PHOTOS';
    EXECUTE IMMEDIATE stmt INTO LINES ;
    for ligne in c1 loop
    exit when loops >= lines ;
    loops := loops+1;
    update photos set img_blob= empty_blob() where CURRENT OF C1;
    -- return img_blob into b_lob;
    b_lob := ligne.img_blob ;
    f_lob := bfilename( 'MY_FILES', ligne.file_name );
    IF (DBMS_LOB.FILEEXISTS(f_lob) != 0)
    THEN
          DBMS_OUTPUT.PUT_LINE('BFILE exist: '|| ligne.file_name || ', ligne :'|| ligne.pk);
          dbms_lob.fileopen(f_lob, dbms_lob.file_readonly);
          dbms_lob.loadfromfile( b_lob, f_lob, dbms_lob.getlength(f_lob) );
          dbms_lob.fileclose(f_lob);
          dbms_output.put_line('ligne.pk :' || ligne.pk || ', lines : ' || lines || ', loops ' || loops);
      ELSE
        DBMS_OUTPUT.PUT_LINE('BFILE does not exist: '|| ligne.file_name || ', ligne :'|| ligne.pk);
      END IF;
    end loop;
    commit;
    end insert_img;

  • Need help: BufferedImage and zooming

    please help me understand what i am doing wrong. i am having a hard time understanding the concept behind BufferedImage and zooming. the applet code loads an image as its background. after loading, you can draw line segments on it. but when i try to zoom in, the image in the background remains the same in terms of size, line segments are the only ones that are being zoomed, and the mouse coordinates are confusing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.net.URL;
    import java.awt.image.*;
    public class Testing extends JApplet {
         private String url;
         private Map map;
         public void init() {
         public void start()
              url = "http://localhost/image.gif";
                  map = new Map(url);
                 getContentPane().add(map, "Center");
                 validate();
                 map.validate();
    class Map extends JPanel implements MouseListener, MouseMotionListener{
         private Image image;
         private ArrayList<Point2D> points;
         private ArrayList<Line2D> lineSegment;
         private Point2D startingPoint;
         private int mouseX;
         private int mouseY;
         private BufferedImage bimg;
         private AffineTransform xform;
         private AffineTransform inverse;
         private double zoomFactor = 1;
         public Map(String url)
                         super();
              //this.image = image;
              try
                   image = ImageIO.read(new URL(url));
              catch(Exception e)
              Insets insets = getInsets();
              xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
              xform.scale(zoomFactor,zoomFactor);
              try {
                   inverse = xform.createInverse();
              } catch (NoninvertibleTransformException e) {
                   System.out.println(e);
              points = new ArrayList();
              startingPoint = new Point();
              bimg = new BufferedImage(this.image.getWidth(this), this.image.getHeight(this), BufferedImage.TYPE_INT_ARGB);
              repaintBImg();
              addMouseListener(this);
              addMouseMotionListener(this);
         public void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D)g;
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            bimg = (BufferedImage)image;
            g2d.drawRenderedImage(bimg, xform);
            if(!points.isEmpty())
                 for(int i=0; i<points.size(); i++)
                      if(i > 0)
                           drawLineSegment(g2d,points.get(i-1),points.get(i));
                      drawPoint(g2d, points.get(i));
            if(startingPoint != null)
                drawTempLine(startingPoint, g2d);
            else
                mouseX = 0;
                mouseY = 0;
         private void repaintBImg()
              bimg.flush();
              Graphics2D g2d = bimg.createGraphics();
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            g2d.drawRenderedImage(bimg, xform);
            g2d.dispose();
         private void drawPoint(Graphics2D g2d, Point2D p)
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
              g2d.setColor(Color.ORANGE);
              g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
         private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2)
              double x1 = p1.getX() * zoomFactor;
                 double y1 = p1.getY() * zoomFactor;
                 double x2 = p2.getX() * zoomFactor;
                 double y2 = p2.getY() * zoomFactor;
                 g2d.setColor(Color.RED);
                 g2d.setStroke(new BasicStroke(3.0F));
                 g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
             private void drawTempLine(Point2D p, Graphics2D g2d)
                 int startX = (int)(p.getX() * zoomFactor);
                 int startY = (int)(p.getY() * zoomFactor);
                 if(mouseX != 0 && mouseY != 0)
                         g2d.setColor(Color.RED);
                          g2d.setStroke(new BasicStroke(2.0F));
                          g2d.drawLine(startX, startY, mouseX, mouseY);
         public void mouseClicked(MouseEvent e)
         public void mouseDragged(MouseEvent e)
              mouseX = (int)(e.getX()*zoomFactor);
              mouseY = (int)(e.getY()*zoomFactor);
              repaint();
         public void mousePressed(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
                   if(points.size() > 0)
                        startingPoint = points.get(points.size()-1);
                        mouseX = mouseY = 0;
                   repaint();
              else if(e.getButton() == 2)
                   zoomFactor = zoomFactor + .05;
                   repaintBImg();
              else if(e.getButton() == 3)
                   zoomFactor = zoomFactor - .05;
                   repaintBImg();
         public void mouseReleased(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
              repaint();
         public void mouseEntered(MouseEvent mouseevent)
         public void mouseExited(MouseEvent mouseevent)
         public void mouseMoved(MouseEvent mouseevent)
    }Message was edited by:
    hardc0d3r

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import java.io.*;
    import java.net.URL;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ZoomTesting extends JApplet {
        public void init() {
            //String dir = "file:/" + System.getProperty("user.dir");
            //System.out.printf("dir = %s%n", dir);
            String url = "http://localhost/image.gif";
                         //dir + "/images/cougar.jpg";
            MapPanel map = new MapPanel(url);
            getContentPane().add(map, "Center");
        public static void main(String[] args) {
            JApplet applet = new ZoomTesting();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class MapPanel extends JPanel implements MouseListener, MouseMotionListener {
        private BufferedImage image;
        private ArrayList<Point2D> points;
        private Point2D startingPoint;
        private int mouseX;
        private int mouseY;
        private AffineTransform xform;
        private AffineTransform inverse;
        RenderingHints hints;
        private double zoomFactor = 1;
        public MapPanel(String url) {
            super();
            try {
                image = ImageIO.read(new URL(url));
            } catch(Exception e) {
                System.out.println(e.getClass().getName() +
                                   " = " + e.getMessage());
            Map<RenderingHints.Key, Object> map =
                        new HashMap<RenderingHints.Key, Object>();
            map.put(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            map.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints = new RenderingHints(map);
            setTransforms();
            points = new ArrayList<Point2D>();
            startingPoint = new Point();
            addMouseListener(this);
            addMouseMotionListener(this);
        private void setTransforms() {
            Insets insets = getInsets();
            xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
            xform.scale(zoomFactor,zoomFactor);
            try {
                inverse = xform.createInverse();
            } catch (NoninvertibleTransformException e) {
                System.out.println(e);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setRenderingHints(hints);
            g2d.drawRenderedImage(image, xform);
            if(!points.isEmpty()) {
                for(int i=0; i<points.size(); i++) {
                    if(i > 0)
                        drawLineSegment(g2d,points.get(i-1),points.get(i));
                    drawPoint(g2d, points.get(i));
            if(startingPoint != null) {
                drawTempLine(startingPoint, g2d);
            } else {
                mouseX = 0;
                mouseY = 0;
        private void drawPoint(Graphics2D g2d, Point2D p) {
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
            g2d.setColor(Color.ORANGE);
            g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
        private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2) {
            double x1 = p1.getX() * zoomFactor;
            double y1 = p1.getY() * zoomFactor;
            double x2 = p2.getX() * zoomFactor;
            double y2 = p2.getY() * zoomFactor;
            g2d.setColor(Color.RED);
            g2d.setStroke(new BasicStroke(3.0F));
            g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
        private void drawTempLine(Point2D p, Graphics2D g2d) {
            int startX = (int)(p.getX() * zoomFactor);
            int startY = (int)(p.getY() * zoomFactor);
            if(mouseX != 0 && mouseY != 0) {
                g2d.setColor(Color.RED);
                g2d.setStroke(new BasicStroke(2.0F));
                g2d.drawLine(startX, startY, mouseX, mouseY);
        public void mouseClicked(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {
            mouseX = (int)(e.getX()*zoomFactor);
            mouseY = (int)(e.getY()*zoomFactor);
            repaint();
        public void mousePressed(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
                if(points.size() > 0) {
                    startingPoint = points.get(points.size()-1);
                    mouseX = mouseY = 0;
            } else if(e.getButton() == 2) {
                zoomFactor = zoomFactor + .05;
                setTransforms();
            } else if(e.getButton() == 3) {
                zoomFactor = zoomFactor - .05;
                setTransforms();
            repaint();
        public void mouseReleased(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
            repaint();
        public void mouseEntered(MouseEvent mouseevent) {}
        public void mouseExited(MouseEvent mouseevent) {}
        public void mouseMoved(MouseEvent mouseevent) {}
    }

  • Getting rgb values from BufferedImage

    BufferedImage.getRGB(int x, int y) returns the colour of an image pixel as an integer. My problem is that i need the seperate red/blue/green components of this. Does anyone know how I can get these?
    Thanks.

    I've done that before but cant actually remember howe to go about it ... but here is an idea that should work
    Color TEMP = new Color(BufferedImage.getRGB(int x, int y)) ;
    Now to extract each component just use the methods getRed() getGreen() and getBlue() on TEMP.
    Does it make sence to you?
    If it does work let me know, just out of curiosity!
    Rui

  • Reading a pdf file from URL into Byte array/ByteBuffer in an applet.

    I'm trying to figure out why this particular snippet of code isn't working for me. I've got an applet which is supposed to read a .pdf and display it with a pdf-renderer library, but for some reason when I read in the .pdf files which sit on my server, they end up as being corrupt. I've tested it by writing the files back out again.
    I've tried viewing the applet in both IE and Firefox and the corrupt files occur. Funny thing is, when I trying viewing the applet in Safari (for Windows), the file is actually fine! I understand the JVM might be different, but I am still lost. I've compiled in Java 1.5. JVMs are 1.6. The snippet which reads the file is below.
    public static ByteBuffer getAsByteArray(URL url) throws IOException {
            ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
            URLConnection connection = url.openConnection();
            int contentLength = connection.getContentLength();
            InputStream in = url.openStream();
            byte[] buf = new byte[512];
            int len;
            while (true) {
                len = in.read(buf);
                if (len == -1) {
                    break;
                tmpOut.write(buf, 0, len);
            tmpOut.close();
            ByteBuffer bb = ByteBuffer.wrap(tmpOut.toByteArray(), 0,
                                            tmpOut.size());
            //Lines below used to test if file is corrupt
            //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
            //fos.write(tmpOut.toByteArray());
            return bb;
    }I must be missing something, and I've been banging my head trying to figure it out. Any help is greatly appreciated. Thanks.

    Keshav.. wrote:
    I too was going through the same problem but I found for some pdfs it worked fine.I didnt get ur solution.Please explain bcoz it may work for every pdfThis thread is over 3 years old and dead. Please open a new thread which provides details of the problem you are having. Link to this thread if you think it is necessary.
    I shall lock this thread.

  • BufferedImage doesn't draw every gif

    hi all,
    I create a buffered Image which should show 2 different gifs (not animated). my problem is that it draws only one of them. I don't think that it has to do with the gif itself because I tried the same drawing without buffering and everything could be seen.
    private BufferedImage bufferedBG;
    setBG();
    private void setBG() { 
    Image linieH = getToolkit().getImage(getClass().getResource("img/bg_linieH.gif"));
    Image linieV = getToolkit().getImage(getClass().getResource("img/bg_linieV.gif"));
    setBackground( Color.WHITE );
    bufferedBG = new BufferedImage( 676 + OFFSET_X, 578, BufferedImage.TYPE_INT_ARGB );
    Graphics2D g = bufferedBG.createGraphics();
    g.drawImage(linieH, 100,200, this);
    g.drawImage(linieV, 150,300, this);
    public void paint( Graphics g ) {
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage( bufferedBG, null, 0, 0 );
    any ideas?
    thanks
    gammloop

    I strongly suspect that what we have here may be confusion about user space and device space..
    The Graphics2D instance in your image class DOES NOT share coords with your paint(Graphics g)
    instance! Its x, y start is 0, 0 and bears no relation to the position on-screen of the component you are
    trying to paint...

  • BufferedImage displays as streaky; smooth image not produced

    Hi all,
    I have three classes that I'm working with. One is ImageProcessor, a Class I have to process images. Another is IMAQGUI, a GUI for my IMAQ service, and the third is IMAQIceStormService.
    In IMAQIceStormService, I am using ImageProcessor to create an image from a byte[] that gets sent to me, and I'm using IMAQGUI to display the image on my GUI.
    All this is working fine, except the image does not display properly. I am getting the proper data, as I have compared the camera image to my streaky image, and saw that they are the same. The width, height, depth, and stride should all be correct; 1000x1000 pixels, 8 bits per pixel, and a stride of 0. I recently changed my ImageProcessor code to make some methods static, and I may have broken something.
    Basically, can anyone take a look at my ImageProcessor methods, and possibly give any suggestions as to why the image is not displaying correctly?
    Here is the relevant part of IMAQIceStormService:
         public void imageAcquired(long id, IMAQTypes.ImageDesc imageDesc, byte[] imageData,
              Ice.Current current) {
              IMAQGUI.appendImage(ImageProcessor.createImage(imageData, imageDesc.width, imageDesc.height));
         }IMAQTypes.ImageDesc is simply the image description. It tells me the width, height, depth, and stride of the image. As you can see, I am telling IMAQGUI to appendImage based on what returns from ImageProcessor. First, here is the relevant code from IMAQGUI:
         private static JLabel imageViewer = new JLabel(); // this gets added to the main panel in a different method
         public static void appendImage(BufferedImage image) {
              imageViewer.setIcon(new ImageIcon(image));
              imageViewer.revalidate();
         }This just sets the icon to the new image, and revalidates the JLabel so it displays the new image.
    Finally, here is the most important part. This is the relevant code from ImageProcessor:
        public static BufferedImage toImage(byte[] data, int w, int h) {
            DataBuffer buffer = new DataBufferByte(data, data.length);
            WritableRaster raster = Raster.createInterleavedRaster(buffer, w, h, w,
            1, new int[] {
                0
            } , null);
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            ColorModel cm = new ComponentColorModel(cs, false, true,
            Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            return new BufferedImage(cm, raster, false, null);
        public static BufferedImage createImage(byte[] data, int width, int height) {
              BufferedImage im = toImage(data, width, height);
            //image = toImage(data, width, height);
            BufferedImage out = createRGBImage(im);
            return out;
        public static BufferedImage createRGBImage(BufferedImage in) {
            BufferedImage output = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D g = output.createGraphics();
            g.drawRenderedImage(in, null);
            g.dispose();
            return output;
        }I am unsure of why ImageProcessor is creating a streaky image, especially because I know the image dimensions are correct. Is there something I am missing? Does anyone see any mistakes anywhere? Does anyone have any suggestions?
    I know this is a lot of information, so thanks a lot for any help you can provide.

    Hi again,
    I'm still unsure as to what the problem is here. I thought maybe it had something to do with the GUI container, but I saved the BufferedImage to the local filesystem using ImageIO.write(), and it looks the same.
    Although no one has apparently seen any obvious problems, can someone possibly let me know if the methods are correct for what I am trying to do: convert a byte[] to a BufferedImage of RGB format?

  • Loading a raw image in BufferedImage

    Hi guys,
    I'm very new to java .I have a raw image which has 32 bit pixels which has ABGR...with alpha as the most signficant byte and the red as the least significant byte. I have an array of ints and I want to load this to a BufferedImage object. I then use a JPanel and render the BufferedImage on to it. I tried doing with other file formats like jpg , gifs and so the rendering to the JPanel works fine. But I'm not able to get the array of ints to be stored in BufferedImage correctly. Could you please let me know what I did was wrong or any suggestions?
    Currently I have a class called RGBAImage that reads the raw image and stores it as an array of ints.
    So in order to create a BufferedImage I do this roughly,
    DataBufferInt buffer = new DataBufferInt(img.getPixels() , img.getPixels().length) ;
    //                                                        bits  red                   green                   blue                 alpha
    ColorModel cm = new DirectColorModel(32, (int)0x000000ff , (int)0x0000ff00 , (int)0x00ff0000 , (int)0xff000000) ;
    SampleModel sm = cm.createCompatibleSampleModel(img.getWidth , img.getHeight) ;
    WriteableRaster raster = Raster.createWritableRaster(sm , buffer , null) ;
    BufferedImage bimg = new BufferedImage(cm , raster , false , null) ;Is this how its to be done? I am not getting the image drawn on the panel. Any suggestions or links?
    Thank you
    Siddharth

    I have an array of ints and I want to load this to a BufferedImage object.In your sample code I cannot see how the int array you are talking about becomes the image data. Also, what is the img variable? Please provide a more complete code sample.

  • 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 !!!

  • How to convert BufferedImage back to Image

    I have an Image from ImageIcon and i want to cut it using BufferedImage.getSubImage(...) and now from BufferedImage i want to turn it to Image again so that i can put in ImageIcon.
    Here is my code:
    URL img = new URL(location);
    ImageIcon imgIcon = new ImageIcon(img);
    Image image = imgIcon.getImage();
    //turn image into bufferedImage via graphic draw
    BufferedImage bi = new BufferedImage(..);
    Graphics g = bi.createGraphics();
    g.drawImage(image,0,0,null);
    bi.getSubImage(...);
    // how to turn bi back to Image newImage
    any ideas??

    More correctly, BufferedImage extends Image as Image is an abstract class and not an interface.
    Shaun

  • How can I convert an Image ( or BufferedImage ) to Base64 format ?

    Hi folks...
    How can I convert an Image, or BufferedImage, to the Base64 format ?
    The image that I want to convert, I get from the webCam connected to the computer...
    Anyone can help me ?
    Rodrigo Kerkhoff

    I suggest you read this thread concerning this:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=477461
    Failing that, Google is your friend.
    Good luck!

Maybe you are looking for