Construct image from Array of pixels

Here's my problem:
I've managed to call the pixelgrabber method on an image, so i've got a 1d array of pixels. Now i want to use that array to create the image within the internal frame so that the image can be changed quickly when the contents of the array change. I was wondering whether using the paint method and mofiying it in some way is the way to go, or is there a much better way to do it?

i'm guessing that no one knows an answer?Bad guess. I know the answer.
The solution lays in the correct use of the following classes:
BufferedImage
WritableRaster
DataBuffer
SampleModel
ColorModel
It goes something like this:
1) Wrap a raw array (probably bytes or ints) in a DataBuffer.
2) Create a SampleModel that describes the layout of the raw data.
3) Now create a WritableRaster that wraps the DataBuffer and SampleModel
4) Create a ColorModel that describes how the raw data maps to the color of a pixel.
5) A BufferedImage can be created from the WritableRaster and the ColorModel.
Drawing operations on the BufferedImage's Graphics2D objects will be reflected in the raw data array. And modifications to the raw data array will be shown when the BufferedImage is drawn onto other Graphics.

Similar Messages

  • Create Image from Array of Pixels

    Greetings:
    I am trying to create an industry standard image (jpeg, tiff) from a raw data format. I am getting mixed up as to which classes to use. The data itself is in binary little-endian. I am using a ByteBuffer to readInt()s in the correct byte order. It appears that I am reading all of the input data ok, but I can't get the actual image creation part of the code. I would appreciate any insight offered as I think this likely not the best approach to solving the problem. Thank you for your time.
    My code is as follows:
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.nio.*;
    public class Main {
        public static void main(String[] args) throws IOException {
            final int H = 2304;
            final int W = 3200;
            byte[] pixels = createPixels(W*H);
            BufferedImage image = toImage(pixels, W, H);
            display(image);
            ImageIO.write(image, "jpeg", new File("static.jpeg"));
        public static void _main(String[] args) throws IOException {
            BufferedImage m = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY);
            WritableRaster r = m.getRaster();
            System.out.println(r.getClass());
        static byte[] createPixels(int size) throws IOException {
            int newsize = size*4;
            byte[] pixels = new byte[newsize];
            String filename = "Run 43.raw";
            InputStream inputStream = new FileInputStream(filename);
            int offset = 0;
            int numRead = 0;
            while (offset < pixels.length
                    && (numRead=inputStream.read(pixels, offset, pixels.length-offset)) >= 0) {
                offset += numRead;
            return pixels;
        static BufferedImage toImage(byte[] pixels, int w, int h) {
            ByteBuffer byteBuffer = ByteBuffer.wrap(pixels);
            byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
            int trash = byteBuffer.getInt(); // strip width
            trash = byteBuffer.getInt(); // strip height
            int[] fixedOrder = new int[2304*3200];
            for (int i=0; i < (2303*3199); i++) {
                fixedOrder[i] = byteBuffer.getInt();
            System.out.println(fixedOrder.length);
            DataBuffer db = new DataBufferInt(fixedOrder, w*h);
            WritableRaster raster = Raster.createPackedRaster(db,
                w, h, 1, new int[]{0}, null);
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            ColorModel cm = new ComponentColorModel(cs, false, false,
                Transparency.OPAQUE, DataBuffer.TYPE_INT);
            return new BufferedImage(cm, raster, false, null);
        static void display(BufferedImage image) {
            final JFrame f = new JFrame("");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JLabel(new ImageIcon(image)));
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

    I have modified my code to be easier to read and it now compiles and builds without errors, however the image it produces is all black and the jpeg it writes is 0 bytes.
    Note: This code was modified from a forum post by user DrLaszloJamf. Thank you for your starting point.
    import java.io.*;
    import java.nio.*;
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.swing.*;
    import javax.imageio.*;
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
        public static void main(String[] args) throws IOException {
            final int width = 2304;
            final int height = 3200;
            final int bytesInHeader = 4;
            final int bytesPerPixel = 2;
            final String filename = "Run 43.raw";
            InputStream input = new FileInputStream(filename);
            byte[] buffer = new byte[(width*height*bytesPerPixel)+bytesInHeader];
            System.out.println("Input file opened. Buffer created of size " + buffer.length);
            int numBytesRead = input.read(buffer);
            System.out.println("Input file read. Buffer has " + numBytesRead + " bytes");
            long numBytesSkipped = input.skip(4);
            System.out.println("Stripped header. " + numBytesSkipped + " bytes skipped.");
            ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
            byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
            System.out.println("Created ByteBuffer to fix little endian.");
            short[] shortBuffer = new short[width*height];
            for (int i = 0; i < (width-1)*(height-1); i++) {
                shortBuffer[i] = byteBuffer.getShort();
            System.out.println("Short buffer now " + shortBuffer.length);
            DataBuffer db = new DataBufferUShort(shortBuffer, width*height);
            System.out.println("Created DataBuffer");
            WritableRaster raster = Raster.createInterleavedRaster(db,
                width, height, width, 1, new int[]{0}, null);
            System.out.println("Created WritableRaster");
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            System.out.println("Created ColorSpace");
            ColorModel cm = new ComponentColorModel(cs, false, false,
                Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
            System.out.println("Created ColorModel");
            BufferedImage bi = new BufferedImage(cm, raster, false, null);
            System.out.println("Combined DataBuffer, WritableRaster, ColorSpace, ColorMode" +
                    " into Buffered Image");
            ImageIO.write(bi, "jpeg", new File("test.jpeg"));
            display(bi);
            System.out.println("Displaying image...");
        static void display(BufferedImage image) {
            final JFrame f = new JFrame("");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JLabel(new ImageIcon(image)));
            f.pack();
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • How can i load or put an image into array of pixels?

    i am doing my undergraduate project , i am using java , mainly the project works in image manipulating or it is image relevant , few days ago i stucked in a little problem , my problem is that i want to put an image scanned from scanner into array or anything ( that makes me reach my goal which is go to specific locations in the image to gather the pixel colour on that location ) , for my project that's so critical to complete the job so , now am trying buffered image but i think it will be significant if i find another way to help , even it isn't in java i heared that matlab has such tools & libraries to help
    thanks .....
    looking forward to hearing from you guys
    Note : My project is java based .

    Check out the PixelGrabber class: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/PixelGrabber.html
    It's pretty simple to get an array of Color objects - or you could just leave it as an int array - though it can be somewhat slow.
    //img - Your img
    int[] pix=new int[img.getWidth(null)*img.getHeight(null)];
    PixelGrabber grab=new PixelGrabber(img,0,0,img.getWidth(null),img.getHeight(null),pix,0,img.getWidth(null));
    grab.grabPixels();  //Blocks, you could use startGrabbing() for asynchronous stuff
    Color[] colors=new Color[pix.length];
    for(int in1=0;in1<colors.length;in1++){
    colors[in1]=new Color(pix[in1],true);  //Use false to ignore Alpha channel
    }//for
    //Colors now contains a Color object for every pixel in the image//Mind you, I haven't compiled this so there could be errors; but I've used essentially the same code many times with few difficulties.

  • Captivate 5 - Inserted PNG images from Fireworks are pixelated

    The PNG images I inserted from Fireworks are showing up pixelated when I play the file in a browser, but look fine while I'm working in Captivate.  Any thoughts?
    THANKS!
    Birgit

    Hello,
    Did you try changing the publish quality? Because of the fact that CP when converting to SWF will still be doing some compression, I really would give that first of all a try.
    PNG allows even partial transparency, and certainly its 24-bit version. That is one of the reasons that it is superior to JPEG (no transparency) and GIF (only 100% transparency).  But I'm not really used to Fireworks, always using Photoshop for graphical assets.
    Lilybiri

  • Exported images from Illustrator look pixelated in Captivate

    Every image I've created in Illustrator and exported to .gif, .jpg or .png all seem pixelated and fuzzy in Captivate 8. Any tips or advice on how to remedy this?
    Mark

    The zoom setting doesn't seem to fix anything since it is when I preview or publish it...correct me if I'm wrong, fairly new to Captivate.
    As far as the pixel grid, it is aligned, but that doesn't seem to fix anything either.
    I talked to Adobe help and they were under the impression there is no way to improve the image quality which seems bizarre to me.

  • Display an image from an array of bytes

    Hi, I'm trying to display an image from the raw pixel values. lets say i read a bmp file to an array, chuk the header off and want to display the pixel. How can I do this? I don't want any file formats, just want to display the pixels and creat the image. Is this possible?
    Many thanks,
    H

    Thanks for the reply. I had a look at MemoryImageSource and other classes that relates to it. I wrote the example given, but it doesn't identify createImage(). I've implemented ImageProducer, but still complains. Have you any idea why? Thanks for your help.
    H

  • How to convert a 2D array of pixels in to a grayscale planar image

    Im having following problems, I hope someone may help me.
    1.     I want to convert a 2D array of pixels (Grayscale values) into a Grayscale PlannerImage. I tried the following code I found on net.
    The steps to do this are:
    -Construct a DataBuffer from your data array.
    -Construct a SampleModel describing the data layout.
    -Construct a Raster from the DataBuffer and SampleModel. You can use methods from the RasterFactory class to do this.
    -Construct a ColorModel which describes your data. The factory method PlanarImage.createColorModel(sampleModel) will take care of this for some common cases.
    -Construct a TiledImage with the SampleModel and ColorModel.
    -Populate the TiledImage with your data by using the TiledImage.setData() method to copy your raster into the TiledImage.
    Only the last step involves any actual processing. The rest is just object creation.
    public static RenderedImage createRenderedImage(float[][] theData, int width, int height, int numBands) {
    int len = width * height * numBands;
    Point origin = new Point(0,0);
    // create a float sample model
    SampleModel sampleModel =
    RasterFactory.createBandedSampleModel(DataBuffer.TYPE_FLOAT,width,height,numBands);
    // create a compatible ColorModel
    ColorModel colourModel = PlanarImage.createColorModel(sampleModel);
    // create a TiledImage using the float SampleModel
    TiledImage tiledImage = new TiledImage(origin,sampleModel,width,height);
    // create a DataBuffer from the float[][] array
    DataBufferFloat dataBuffer = new DataBufferFloat(theData, len);
    // create a Raster
    Raster raster = RasterFactory.createWritableRaster(sampleModel,dataBuffer,origin);
    // set the TiledImage data to that of the Raster
    tiledImage.setData(raster);
    RenderedImageAdapter img = new RenderedImageAdapter((RenderedImage)tiledImage);
    return img;
    I passed it 2D array of pixels with 3 bands, and it gave an exception >>Array index out of bounds at this line >>tiledImage.setData(raster). Then I tried it with a 1D array of length height*width with a single band. So Now it gives me a monochromatic RenderedImage. How can I make it a grayscale PlanarImage.

    jyang, thank you very much for your response. I believe I found a different solution all together, by converting each 16-bit intensity value into an 8-bit intensity value via an intensity ratio (ie: divide each intensity by the maximum and multiply by 256). The attachment shows the new program.
    Attachments:
    mod_image.vi ‏2004 KB

  • How to create Image from 8-bit grayscal pixel matrix

    Hi,
    I am trying to display image from fingerprintscanner.
    To communicate with the scanner I use JNI
    I've wrote java code which get the image from C++ as a byte[].
    To display image I use as sample code from forum tring to display the image.
    http://forum.java.sun.com/thread.jspa?forumID=20&threadID=628129
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class Example {
    public static void main(String[] args) throws IOException {
    final int H = 400;
    final int W = 600;
    byte[] pixels = createPixels(W*H);
    BufferedImage image = toImage(pixels, W, H);
    display(image);
    ImageIO.write(image, "jpeg", new File("static.jpeg"));
    public static void _main(String[] args) throws IOException {
    BufferedImage m = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster r = m.getRaster();
    System.out.println(r.getClass());
    static byte[] createPixels(int size){
    byte[] pixels = new byte[size];
    Random r = new Random();
    r.nextBytes(pixels);
    return pixels;
    static BufferedImage toImage(byte[] pixels, int w, int h) {
    DataBuffer db = new DataBufferByte(pixels, w*h);
    WritableRaster raster = Raster.createInterleavedRaster(db,
    w, h, w, 1, new int[]{0}, null);
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorModel cm = new ComponentColorModel(cs, false, false,
    Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm, raster, false, null);
    static void display(BufferedImage image) {
    final JFrame f = new JFrame("");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JLabel(new ImageIcon(image)));
    f.pack();
    SwingUtilities.invokeLater(new Runnable(){
    public void run() {
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    And I see only white pixels on black background.
    Here is description of C++ method:
    GetImage
    Syntax: unsigned char* GetImage(int handle)
    Description: This function grabs the image of a fingerprint from the UFIS scanner.
    Parameters: Handle of the scanner
    Return values: Pointer to 1D-array, which contains the 8-bit grayscale pixel matrix line by line.
    here is sample C++ code which works fine to show image in C++
    void Show(unsigned char * bitmap, int W, int H, CClientDC & ClientDC)
    int i, j;
    short color;
    for(i = 0; i < H; i++) {
         for(j = 0; j < W; j++) {
         color = (unsigned char)bitmap[j+i*W];
         ClientDC.SetPixel(j,i,RGB(color,color,color));
    Will appreciate your help .

    Hi Joel,
    The database nls parameters are:
    select * from nls_database_parameters;
    NLS_LANGUAGE AMERICAN
    NLS_TERRITORY AMERICA
    NLS_CURRENCY $
    NLS_ISO_CURRENCY AMERICA
    NLS_NUMERIC_CHARACTERS .,
    NLS_CHARACTERSET CL8MSWIN1251
    NLS_CALENDAR GREGORIAN
    NLS_DATE_FORMAT DD-MON-RR
    NLS_DATE_LANGUAGE AMERICAN
    NLS_SORT BINARY
    NLS_TIME_FORMAT HH.MI.SSXFF AM
    NLS_TIMESTAMP_FORMAT DD-MON-RR HH.MI.SSXFF AM
    NLS_TIME_TZ_FORMAT HH.MI.SSXFF AM TZR
    NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR
    NLS_DUAL_CURRENCY $
    NLS_COMP BINARY
    NLS_LENGTH_SEMANTICS BYTE
    NLS_NCHAR_CONV_EXCP FALSE
    NLS_NCHAR_CHARACTERSET AL16UTF16
    NLS_RDBMS_VERSION 9.2.0.4.0
    Part of the email header:
    Content-Type: multipart/alternative; boundary="---=1T02D27M75MU981T02D27M75MU98"
    -----=1T02D27M75MU981T02D27M75MU98
    -----=1T02D27M75MU981T02D27M75MU98
    Content-Type: text/plain; charset=us-ascii
    -----=1T02D27M75MU981T02D27M75MU98
    Content-Type: text/html;
    -----=1T02D27M75MU981T02D27M75MU98--
    I think that something is wrong in the WWV_FLOW_MAIL package. In order to send 8-bit characters must be used UTL_SMTP.WRITE_ROW_DATA instead of the UTL_SMTP.WRITE_DATA.
    Regards,
    Roumen

  • Can I convert 3D image to an array of pixels in LabVIEW?

    Hi all;
    I am still new with labview. I has 1 question, can I convert 3D image to an array of pixels using labview?
    Most of the examples I found they only convert 2D image. Hope anyone can give me some hint.
    Thank You

    look at this thread.
    It has links to other threads where the 3D graphs were used.
    You should also search for "gif reader" to find threads where images are read from gif files.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Create an image from float array?

    Dear All,
    I have a float array containing pixel values. From that array I want to create an image (let's say in JPEG format).
    How should I do that?
    thanks

    Hi musti168,
    You're going through your entire image pixel-by-pixel and getting each of their values - why don't you just use the IMAQ ImageToArray function?  
    On this forum post I found an example of IMAQ ArrayToImage: http://forums.ni.com/t5/LabVIEW/IMAQ-arraytoimage-​example/td-p/68418
    You can use some of the IMAQ Image Processing palette to change the image to gray scale - possibly a threshold.
    Julian R.
    Applications Engineer
    National Instruments

  • Locations of all pixels of image into array...

    In my program, the user clicks on my JPanel and an image of a ball about 15 pixels in diameter appears. The user will then click again to add another ball. I can't allow the new ball to be placed where the balls touch or looked like they intersect.
    If I could get all the pixels associated with the first ball into an array, I could test those x,y coordinates against the new ball's and prevent the user from adding a new ball if they intersect.
    Any ideas? I was looking at pixelgrabber, but that seemed like it was about the color of pixels...

    ok so I understand what you are saying... I know the center pixel of the circle when I out it down... so I have by default, the left, right, top, bottom, and 4 corner pixels of the circle.
    Here's the overall picture though... this is a simple billiards project... So I need to write a test that will return true if one ball can make it past another ball into a a pocket without colliding, and false if the balls with hit each other. Thats why I figured I would need all the pixels of each ball in an array to test against, or at least every pixel on its circumference... this is where I get really confused...
    This is what I'm thinking if I can just extract this info: (psydocode)
    Ball ball1 = new Ball(x,y); //class Ball will also contain the array of pixels
    Ball ball2 = new Ball(x,y);
    private boolean shotTest(Ball ball1, Ball ball2)
         int [] array1 = ball1.getArray();
         int [] array2 = ball2.getArray();
         for(int i=0, i<array1.length(); i++)
              for(int j=0; j<array2.length(); j++)
                   if(*straight line from array1[i] to pocket hits array2[j])
                        return false;
         return true;
    }...is that a start?

  • Graphics2D.scale() producing pixelated images from vectors

    I have a set of JPanels that I am using in my game to display the interface. Each one overrides paintComponent() and draws itself using Java2D. That all works great -- you can zoom in, move around, etc. and it all looks very nice and uses affine transformations.
    I'm trying to produce very high resolution images from this interface (for use on a poster) and using scale() is creating pixelated images rather than nice, high res images of the vector data.
    My code works as follows:
    1.) Create an instance of the interface using some saved game state data.
    2.) Create a Graphics2D object from a BufferedImage object.
    3.) Scale the Graphics2D object so that the interface will fill the entire image (in my test cases, the interface is running at 800x600 normally, and the resulting image is going to be 3200x1600, so a 4x scale).
    4.) Call the interface's paint method on the Graphics2D object. Note that all of the paint methods are using calls to fill... and draw...; nothing is getting rasterized in my code.
    5.) Write out the image object to a file (PNG).
    A sample of the output is here:
    http://i176.photobucket.com/albums/w174/toupsz/ScreenShot2007-04-24_11-45-35_-0500.png
    The white circle in the upper left hand corner is drawn in between steps 4 and 5. It actually looks correct.
    Is there something I'm doing wrong? Is it a deficiency in Java itself? Is there some way to fix it?
    Any help would be most appreciated!
    Thanks!
    -Zach
    Message was edited by:
    aaasdf

    Try setting a few hints on your Graphics2D:
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

  • My iphone 4s suddenly displays images from Yahoo, Google, and Flickr at low resolution. The camera on my phone works fine, but any web related photo content is now pixelated and low res, what's the deal?

    My iphone 4s suddenly displays images from Yahoo, Google, and Flickr at a low resolution. I have IOS 7.0.4. My phone camera works fine, but any web based photo content from Safari, Yahoo images, Google images, and Flickr all come in pixelated and low res. What's the deal?

    It happened to me but later I figured out that cellular signal was not that great and so the Internet was very slow. It took me about 2 minutes to get the full resolution picuture on either of the app you've described. Try to get faster internet either by wifi or good signal and then check.

  • If you change the image mode of this image from 8-bit RGB image to Grayscale mode while in PSCS – what will the new Pixel Count be?

    If you change the image mode of this image from 8-bit RGB image to Grayscale
    mode while in PSCS – what will the new Pixel Count be?

    If you mean by Pixel count the number of pixels, this will not change. The image will have the same size thus the same number of pixels.

  • Displaying a picture from an array of pixel values

    I have a picture I want to display in an AWT frame. The picture is stored as several arrays of pixel values which represent rectangles.
    Each rectangle has a start co-ordinate and a height and width.
    There is a ColorModel associated with the pixel values, so that's not a problem.
    What's the best way to display these rectangles as pixels, and patch them all together to make the full picture? I'm currently trying to use a MemoryImageSource, but I'm having trouble displaying more than one rectangle at once, and the picture flickers like mad, suggesting MemoryImageSource intended for animation, whereas I just want to display the picture once.
    Any suggestions?

    OK, that looks good. I'm investigating it.
    However, It's not clear how to get the pixel values from an array into it. It requires a WriteableRaster of the pixel data, and to create a WriteableRaster, you need a DataBuffer... which is Abstract!
    Do you know how to make a DataBuffer from an array?

Maybe you are looking for

  • Opening & closing stock

    Hi Expert,     I am developing one zreport . i want to know how to calculate opening and closing stock using mb5b standard report. Thanks Dinesh

  • Mail / Login in with Gmail/ received email ok but when problem sending.

    I log into my mail using gmail, and was receiving email ok. I tried to send an email to my other gmail account, but it showed up in the spam ?? What's going on? Thanks.

  • Menu Text Rollover Possible?

    I am a classical musician, and I'm creating a DVD of my work to send out to managers and potential sponsors. Towards that end, I've put together an iDVD project using the "Reflection Black" Theme provided within iDVD. For the most part, I'm quite hap

  • Diskutil list not responding

    My 2009 27" iMac has recently stopped working. When I boot up it runs normally for  few minutes and then everything freezes up and I get the beachball. I can move the cursor and drag windows around the desktop but I can't actually click on anything.

  • "Mail was unable to find your reply to the message... You may have deleted the message."

    I'm experiencing some kind of corruption in Mail's ability to connect replies to messages. The error I'm starting to get says this: "Mail was unable to find your reply to the message... You may have deleted the message." And these emails are no longe