BufferedImage

Dear All,
I have the following program from GNome which scan and then cache then image in memory buffer and save as JPEG format. My question is how do I save it as tiff format using the same class BufferImage ? Please advise.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.*;
import SK.gnome.twain.*;
import com.sun.image.codec.jpeg.*;
public class Example3 extends Frame
{ Image image;
int width;
int height;
public void paint(Graphics g)
{ if (null!=image)
g.drawImage(image, 0, 0, this);
public Dimension getPreferredSize()
{ return new Dimension(width, height);
public class WindowListener extends WindowAdapter
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
public void scan() throws TwainException
{ Twain twain=new Twain();
image=Toolkit.getDefaultToolkit().createImage(new TwainImage(twain));
setSize(width=image.getWidth(this), image.getHeight(this));
This method saves a image data to the jpeg file format. It uses
com.sun.image.codec.jpeg package.
public void save() throws Exception
{ File f=new File("test.jpg");
int w=image.getWidth(null);
int h=image.getHeight(null);
BufferedImage bimg=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
bimg.createGraphics().drawImage(image, 0, 0, null);
FileOutputStream out=new FileOutputStream(f);
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param=encoder.getDefaultJPEGEncodeParam(bimg);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(bimg);
out.close();
public Example3() throws Exception
{ addWindowListener(new WindowListener());
setTitle("Example3 Frame Application");
scan();
setVisible(true);
save();
public static void main(String[] args) throws Exception
{ Example3 p=new Example3();
Best Regards

Dear Sir,
Thanks for your prompt reply. I would like to explain my source of problem before going into BufferedImage. You see I have a program which scans multiple images through Auto document feeder(ADF) and what I do is I collect the image_content[] in array for each scan and after finish scanning all the pages, I start from 1st array to the last to encode/save the image one at a time. Now the problem begins when I starts saving/encode, instead of saving immediately, the enc.encode trigger scanning again and wrongly save the newly scan image which is a blank glass, ignoring the image_content[]. Somebody told me that the image_content[] is a pointer to image, not image content itself so he proposed me to buffer image and encode it. Here is my problem source code. Please advise soon as to solving the above problems.
import java.awt.*;
import java.awt.event.*;
import SK.gnome.twain.*;
import javax.media.jai.*;
import java.io.*;
import java.awt.image.*;
import com.sun.media.jai.codec.*;
public class Example9
{ static int frameCount=1;
static int arrayCount=0;
static RenderedOp image_content[]=null;
static class DisplayImage extends Frame
{ Image awt_image;
WindowListener listener=new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
public DisplayImage(TwainSource source) throws NullPointerException
{   super("Image: "+frameCount);
addWindowListener(listener);
     arrayCount = frameCount - 1;
awt_image=Toolkit.getDefaultToolkit().createImage(source);
MediaTracker tracker=new MediaTracker(this);
     System.out.println("Begin tracker add image");
tracker.addImage(awt_image, 0);
try
{ tracker.waitForAll();
catch (InterruptedException e)
     System.out.println("End tRacker add image");
System.out.println("ok" + frameCount);
System.out.println("before_rendered_image_content " + frameCount);
image_content[arrayCount] = (RenderedOp) JAI.create("AWTImage", awt_image);
     System.out.println("after_rendered_image_content " + frameCount);
tracker.removeImage(awt_image);
setSize(new Dimension(awt_image.getWidth(this)+40, awt_image.getHeight(this)+60));
setVisible(true);
     //new SaveImage(image_content);
     frameCount++;
     System.out.println("after plus 1");
public void paint(Graphics g)
{ if (null!=awt_image)
g.drawImage(awt_image, 20, 40, this);
static public void SaveImage(int image_counter)
try{
     System.out.println("Begin try" + image_counter);
//OutputStream os = new FileOutputStream("doc" + image_counter + ".tiff");
     OutputStream os = new FileOutputStream(new File("C:" + File.separator + "iims" + File.separator + "doc" + image_counter + ".tiff"));      
     System.out.println("afteroutputstream " + frameCount);
//int w=image_content.getWidth(null);
//int h=image_content.getHeight(null);
//BufferedImage bimg=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//bimg.createGraphics().drawImage(image_content[image_counter], 0, 0, null);
TIFFEncodeParam param = new TIFFEncodeParam();
//param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);     
ImageEncoder enc = ImageCodec.createImageEncoder("TIFF", os,param);
     System.out.println("before encode image content " + image_counter);
enc.encode(image_content[image_counter]);
     //enc.encode(bimg);
     System.out.println("after enc.encode image content " + image_counter);
os.close();
     System.out.println("after os.close = " + image_counter);
     System.out.println("End try" + image_counter);
catch(IOException ioe)
          System.out.println(ioe);
public static void main(String[] args) throws TwainException
{ TwainSource source=TwainManager.selectSource(null);
//Twain source=new Twain();
// Default values for these settings are set by Twain source.
// All settings are requests only and can be refused.
// Order of settings reguests is not important.
// Settings are sent to Twain source (in the correct order),
// when some consumer calls StartProduction method of the Twain class.
source.setVisible(true);
source.setPixelType(Twain.RGB);
source.setXResolution(75.0);
source.setYResolution(75.0);
// Option for selecting Automatic Document feeder.
source.setFeederEnabled(true);
// When set to true, the behavior of the source is to eject
// one page and feed the next page after frame of the first page is acquired.
source.setAutoFeed(true);
// Setup duplex scanning.
source.setDuplexEnabled(true);
// The number of images requested by the application.
// -1 = Accept any number of images available.
// Scanning capabilities must be set before first scanning.
source.setTransferCount(-1);
// initialise new array
image_content = new RenderedOp[50];
do
{   System.out.println("before call DisplayImage ");
     new DisplayImage(source);
     System.out.println("after call DisplayImage ");
while (source.hasMoreImages());
source.setFeederEnabled(false);
source.setAutoFeed(false);
source.setDuplexEnabled(false);
for (int i=0; i<image_content.length; i++)
     SaveImage(i);
}

Similar Messages

  • 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

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

  • How to create a BufferedImage object using a .png file on harddisk

    For some application of JFreeChart I want to create a BufferedImage object from png file on harddisk.
    Can anybody tell me how to achieve this?
    Thanks in advance.

    See [this thread|http://forum.java.sun.com/thread.jspa?threadID=5144115].

  • Can I write a AVI file adding images (BufferedImages) of one in one?

    Hi!! I show some point clouds in Java3D, then I get the BufferedImages of each scene, but I want to make a AVI file of the following way:
    1)I make (ans I show it) a scene 3D.
    2)I get a BufferedImage of this scene.
    3)I use a JMF processor to add this bufferedImage to the file .AVI.
    4) I return to the step 1).
    Regards!

    If you were using OSX 10.7 then you could go back to a previous version, but you have overwritten the file.
    Peter

  • Can you get the original bytes/format from a BufferedImage

    Applications allows users to select file and then the contents of the files are embedded into an mp3 file, but also allow images to be dragged or copy and pasted and in vertainn cases I only recieve the image as an Image DataFlavor (new DataFlavor("image/x-java-image;class=java.awt.Image");), so I have the bufferedImage but I need to convert into a stream of bytes and I don't have the bytes or even the the orginal format of the image, or are they hidden in the BufferedImage somewhere. At the moment I'm always writing the Bufferedimage as a jpeg whereas Id prefer to write the original format if supported, not least because sometimes ImageIO actually renders the file incorrectly (#4881314 , #6444933).
    thanks Paul

    Not possible. No.

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

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

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

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

Maybe you are looking for

  • How to increase the max connections for business rules.

    How and where to increase the connection to EAS.currently we have max connection as 20.Also please let me know,what is the maximum connection we can increase. In our system totally,we have 350 users are present. when more that 20 users running the bu

  • Installation not starting on IBM T23

    Trying to install Solaris Express, Developer Edition on my IBM T23. Instalation process crash at the beginning with an error: "cannot find framebuffer driver". Need some explanation. Why it happens.

  • HR_ESS_PAYSLIP_TO_PDF - data source for smartform

    Hi freinds, I need to design a z copy of smartform HR_ESS_PAYSLIP_TO_PDF. I would like to know the tables from which i get data(for payslip) to be shown. Please mention, if some tables in smartform are filled with data automatically? Do I need to pul

  • Delete Allowed generation for tables

    At my group level I have set a value for the "Delete Allowed EL expression". In table layout though, it uses this value to set the rendered property of the checkbox rather than the column, meaning the users still see a column called "Delete ?" with j

  • Discoverer EUL5 Status Workbooks

    Hi, We have tried to load the EUL5 Status Workbooks in to our EUL. Two of the 5 workbooks have loaded successfully but "Query Statistics", "Data Definition" and "Workbook Management" have not been imported. This appears to be an Access Privs issue, b