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);
}

Similar Messages

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

  • 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

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

  • Disk Utility fails to create image from double layer DVD

    I burned a double-layer DVD using iDVD. It plays fine on the mac and on set-top DVD players. However, when I try to create an image of the DVD using Disk Utility, I get "Can't create image 'name.cdr' (input/output error)". I've tried re-burning the original disk, but it gets the same error when trying to create an image. I've also tried each of the image types, all with the same result.

    I was having similar problems, although I don't think my issues was related to a double-layer DVD. What worked for me was selecting File > New > Disk Image from Folder. Select the DVD in the file open/save dialog with the same options you used before (e.g., DVD/CD master, etc).
    HTH
    - Dave

  • Disk Utility: Create Image from Volume Without Unused Space

    I'm trying to create a disk image from a mounted volume (flash memory in a video camera) but I don't want to write to it later, it's just for archiving. The problem is that the size of the original volume is 16 GB, so every image I create is huge, even if there is less than a 1 GB used.
    For example, I only have two short clips on there, about 1.1 GB used. When I create a new .dmg from the volume, the file is 5.28 GB and when I mount it it tells me the size of the volume is 15.3 GB. Clearly I understand why this is happening, it's creating a bit for bit copy of the original volume, but I don't need all that space since I'm never going to write to it.
    In disk utility it won't let me resize the image (it's grayed out). What do I do?

    I actually don't understand why this is happening (when I do this the created disk image only uses the space it needs) but you can get around it as follows. First create a blank read/write disk image to the size you want and then restore the memory card to that image.

  • Creating image from text

    Hi guys! I want to write/find a way to create image that contains some text. For example when you sing in to yahoo.com it shows you an immage with text that you should input to prove that you`re registering from the site .. How to do this?

    Hi guys! I want to write/find a way to create image that contains some text. For example when you sing in to yahoo.com it shows you an immage with text that you should input to prove that you`re registering from the site .. How to do this?

  • Problem creating  image from a data vector

    Hello i have a problem in this aplication.
    I get a image from a web cam. I want to put the original image in a file and the negative image in another file (in this example is not the negative image, is just a white image). The problem is when i use setData method. The image become black. If I use setFormat method the new image is the original image.
    Here is the code with problems:
    imageBuffer = frameGrabbingControl.grabFrame();
    theData = new int[dataLength];
    theData = (int[]) imageBuffer.getData();
    for (int y = 0; y < videoHeight - imageScanSkip; y+=imageScanSkip) {
    for (int x = 1; x < videoWidth - imageScanSkip; x+=imageScanSkip)
    theData[y*videoWidth+x]=Integer.parseInt("FFFFFF",16);
    Buffer b1=new Buffer(); //This is the new buffer in which i want to put the new pic
    b1.setData(theData);
    //here i create the 2 files frst from the original buffer and second from the new buffer b1
    Image img = (new BufferToImage((VideoFormat)imageBuffer.getFormat()).createImage(imageBuffer));
    Image img1 = (new BufferToImage((VideoFormat)b1.getFormat()).createImage(b1));
    BufferedImage buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    BufferedImage buffImg1 = new BufferedImage(320,240, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = buffImg.createGraphics();
    Graphics2D g1 = buffImg1.createGraphics();
    g.drawImage(img, null, null);
    g1.drawImage(img1, null, null);
    try{
    ImageIO.write(buffImg, "jpg", new File("c:\\webcam.jpg"));
    ImageIO.write(buffImg1, "jpg", new File("c:\\webcam1.jpg"));
    catch (Exception e){}
    the webcam1.jpg file is black(it should be white).
    If i put "b1.setFormat(imageBuffer.getFormat());" the webcam1.jpg will be same the file as webcam.jpg

    Hello i have a problem in this aplication.
    I get a image from a web cam. I want to put the original image in a file and the negative image in another file (in this example is not the negative image, is just a white image). The problem is when i use setData method. The image become black. If I use setFormat method the new image is the original image.
    Here is the code with problems:
    imageBuffer = frameGrabbingControl.grabFrame();
    theData = new int[dataLength];
    theData = (int[]) imageBuffer.getData();
    for (int y = 0; y < videoHeight - imageScanSkip; y+=imageScanSkip) {
    for (int x = 1; x < videoWidth - imageScanSkip; x+=imageScanSkip)
    theData[y*videoWidth+x]=Integer.parseInt("FFFFFF",16);
    Buffer b1=new Buffer(); //This is the new buffer in which i want to put the new pic
    b1.setData(theData);
    //here i create the 2 files frst from the original buffer and second from the new buffer b1
    Image img = (new BufferToImage((VideoFormat)imageBuffer.getFormat()).createImage(imageBuffer));
    Image img1 = (new BufferToImage((VideoFormat)b1.getFormat()).createImage(b1));
    BufferedImage buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    BufferedImage buffImg1 = new BufferedImage(320,240, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = buffImg.createGraphics();
    Graphics2D g1 = buffImg1.createGraphics();
    g.drawImage(img, null, null);
    g1.drawImage(img1, null, null);
    try{
    ImageIO.write(buffImg, "jpg", new File("c:\\webcam.jpg"));
    ImageIO.write(buffImg1, "jpg", new File("c:\\webcam1.jpg"));
    catch (Exception e){}
    the webcam1.jpg file is black(it should be white).
    If i put "b1.setFormat(imageBuffer.getFormat());" the webcam1.jpg will be same the file as webcam.jpg

  • Create methods from array

    Hello all,
    I want to know if I can create methods from writing them by using a for loop?
    I think I should use setmethod, but I can't find an example that I understand - yes I'm a newbie :-). So if anyone can point me to the right direction! Here is the code;
    class commands {
    String [] commandos = {"open", "play", "exit", "help"};
    int i, z;
    String str = new String();
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(reader);
    public commands() {
    /* methods I want to implement
    for (z=0; z < commandos.length; z++) {
    public void commandos[z]() { // syntax I want to implement
    System.out.println("Commando " + commandos[z] + " is being executed");
    try {
      do {
      str = br.readLine ();
         for (i=0; i < commandos.length; i++) {
         if (str.toLowerCase().equals (commandos)) {
         System.out.println("Commando " + commandos[i] + " is being executed"); // needs replacement
    } while (!str.toLowerCase().equals ("quit"));
    catch (IOException e) { System.out.println("IOexception = " + e );}
    public class comecho {
    public static void main (String [] args) {
    commands com = new commands();

    Thanks for the quick reply. Bummer it can't be done that though. I'll live with it.
    I slightly changed the code to see if I can achieve the following.
    I want to call one function when array value equals a method name. Is this possible?
    import java.io.*;
    class commands {
    String [] commandos = {"open", "play", "exit", "help"};
    int i, z;
    String str = new String();
    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(reader);
    public commands() {
    // public void open() { }
    // public void play() { }
    // public void exit() { }
    // public void help() { }
    try {
      do {
      str = br.readLine ();
         for (i=0; i < commandos.length; i++) {
         if (str.toLowerCase().equals (commandos)) {
         System.out.println("nothing"); // How to convert commandos[i] to call function commandos[i]
    } while (!str.toLowerCase().equals ("quit"));
    catch (IOException e) { System.out.println("IOexception = " + e );}
    public class comecho {
    public static void main (String [] args) {
    commands com = new commands();

  • How to create jpegs from pdfs without pixellated results

    I have been creating jpegs from high quality pdfs (typically 20-30 MB files) of maps (paper dimensions roughly 2 ft by 3 ft) with no problems until this week.  I use the export function in Adobe X Standard and select jpeg.  Did I recently get an update which changed my settings?  Now I notice that sometimes the process generates a progress bar which says it is optimizing the content for the web.  I don't remember seeing this either.  Previous conversions worked great and the jpegs could be blown up on the screen with crisp detail.  Yesterday I did the same process with a new map (I checked it for good resolution and the pdf can be zoomed way in with no loss of resolution). But the resulting jpeg pixellates very quickly when zooming in.  What gives?  It may be possible that this new map (pdf) is in layers.  I think the others were scans of the paper maps.  Does this affect the conversion?  Also noticed that the jpegs now have little lock symbols on them.  Is that related?  I don't think it is, because a map I recently converted has the lock symbol on it and is OK (as a jpeg).  I am converting the pdfs into jpegs so I can import them into Autocad.

    As the helpcenter(2005 helpcenter) has missed this bit of documentation (on UserQueries) could someone please provide an example of using this object
    thanks
    Message was edited by: George Savery
    hmm I thought it had timed out .... Woops

  • Create image from byte[]array on server side

    Hello everyone..
    I'm developing an application which will take snapshots from a mobile device, and send it to my pc via bluetooth. I have my own midlet which uses the phone camera to take the snapshot, i want to transfer that snapshot to my pc.
    The snapshot is taken is stored in an array byte.
    The image can be created on the phone itself with no problem using : image.createImage(byte[])
    my problem is that when i send the array byte via bluetooth, and receive it on the server, i cannot create the image using the :image.createImage() code
    The connection is good since i have tested by writing the content of the array in a text file.
    Piece of midlet code:
                try{
                     stream = (StreamConnection)Connector.open(url);
                     OutputStream ggt = stream.openOutputStream();
                     ggt.write(str);
                     ggt.close();
                }catch(Exception e){
                     err1  = e.getMessage();
                }where str is my array byte containing the snapshot
    And on my server side:
    Thread th = new Thread(){
                   public void run(){
                        try{
                             while(true){
                                  byte[] b = new byte[in.read()];
                                  int x=0;
                                  System.out.println("reading");
                                  r = in.read(b,0,b.length);
                                  if (r!=0){
                                       System.out.println(r);     
                                       img = Image.createImage(b, 0, r);
                                                            //other codes
                                       i get this error message:
    Exception in thread "Thread-0" java.lang.UnsatisfiedLinkError: javax.microedition.lcdui.ImmutableImage.decodeImage([BII)V
         at javax.microedition.lcdui.ImmutableImage.decodeImage(Native Method)
         at javax.microedition.lcdui.ImmutableImage.<init>(Image.java:906)
         at javax.microedition.lcdui.Image.createImage(Image.java:367)
         at picserv2$1.run(picserv2.java:70)
    Please anyone can help me here? is this the way to create the image on the server side? thx a lot

    here is exactly how i did it :
    while(true){
                                  byte[] b = new byte[in.read()];
                                  System.out.println("reading");
                                  r = in.read(b, 0, b.length);
                                  if (r!=0){
                                       Toolkit toolkit = Toolkit.getDefaultToolkit();
                                       Image img = toolkit.createImage(b, 0, b.length);
                                       JLabel label = new JLabel(new ImageIcon(img) );
                                       BufferedImage bImage = new BufferedImage(img.getWidth(label),img.getHeight(label),BufferedImage.TYPE_INT_RGB);
                                       bImage.createGraphics().drawImage(img, 0,0,null);
                                       File xd = new File("D:/file.jpg");
                                       ImageIO.write(bImage, "jpg", xd);
                                       System.out.println("image sent");
                             }Edited by: jin_a on Mar 22, 2008 9:58 AM

  • Create Image from Stream in Applet via Servlet

    First of all, I apologize if this isn't posted to the proper forum, as I am dealing with several topics here. I think this is more of an Image and I/O problem than Applet/Servlet problem, so I thought this forum would be most appropriate. It's funny...I've been developing Java for over 4 years and this is my first post to the forums! :D
    The problem is I need to retrieve a map image (JPEG, GIF, etc) from an Open GIS Consortium (OGC) Web Map Server (WMS) and display that image in an OpenMap Applet as a layer. Due to the security constraints on Applets (e.g., can't connect to a server other than that from which it originated), I obviously just can't have the Applet create an ImageIcon from a URL. The OpenMap applet will need to connect to many remote WMS compliant servers.
    The first solution I devised is for the applet to pass the String URL to a servlet as a parameter, the servlet will then instantiate the URL and also create the ImageIcon. Then, I pass the ImageIcon back to the Applet as a serialized object. That works fine...no problems there.
    The second solution that I wanted to try was to come up with a more generic and reusable approach, in which I could pass a URL to a servlet, and simply return a stream, and allow the applet to process that stream as it needs, assuming it would know what it was getting from that URL. This would be more usable than the specific approach of only allowing ImageIcon retrieval. I suppose this is actually more of a proxy. The problem is that the first few "lines" of the image are fine (the first array of buffered bytes, it seems) but the rest is garbled and pixelated, and I don't know why. Moreover, the corruption of the image differs every time I query the server.
    Here are the relevant code snippets:
    =====================Servlet====================
        /* Get the URL String from the request parameters; This is a WMS
         * HTTP request such as follows:
         * http://www.geographynetwork.com/servlet/com.esri.wms.Esrimap?
         *      VERSION=1.1.0&REQUEST=GetMap&SRS=EPSG:4326&
         *      BBOX=-111.11361,3.5885315,-48.345818,71.141304&
         *      HEIGHT=480&...more params...
         * It returns an image (JPEG, JPG, GIF, etc.)
        String urlString =
            URLDecoder.decode(request.getParameter("wmsServer"),
                              "UTF-8");
        URL url = new URL(urlString);
        log("Request parameter: wmsServer = " + urlString);
        //Open and instantiate the streams
        InputStream urlInputStream = url.openStream();
        BufferedInputStream bis = new
            BufferedInputStream(urlInputStream);
        BufferedOutputStream bos = new
            BufferedOutputStream(response.getOutputStream());
        //Read the bytes from the in-stream, and immediately write them
        //out to the out-stream
        int read = 0;
        byte[] buffer = new byte[1024];
        while((read = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, buffer.length);
        //Flush and close
        bos.flush();
        urlInputStream.close();
        bis.close();
        bos.close();
        .=====================Applet=====================
        //Connect to the Servlet
        URLConnection conn = url.openConnection();
        conn.setUseCaches(false);
        conn.setRequestProperty("header", "value");
        conn.setDoOutput(true);
        //Write the encoded WMS HTTP request
        BufferedWriter out =
            new BufferedWriter( new OutputStreamWriter(
                conn.getOutputStream() ) );
        out.write("wmsServer=" + URLEncoder.encode(urlString, "UTF-8"));
        out.flush();
        out.close();
        //Setup the streams to process the servlet response
        BufferedInputStream bis = new
            BufferedInputStream(conn.getInputStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //Read the bytes and immediately write to the out-stream
        int read = 0;
        byte[] buffer = new byte[1024];
        while((read = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, buffer.length);
        //Flush and close
        bis.close();</code>
        bos.flush();</code>
        byte[] imageBytes = bos.toByteArray();
        //Create the Image/ImageIcon
        Toolkit tk = Toolkit.getDefaultToolkit();
        Image image = tk.createImage(imageBytes);
        imageIcon = new ImageIcon(image);
        Could this be an offset problem in my buffers? Is there some sort of encoding/decoding I am missing somewhere?
    Thanks!
    Ben

    Without having a probing look, I was wondering why you do the following...
    while((read = bis.read(buffer, 0, buffer.length)) != -1) {
    bos.write(buffer, 0, buffer.length);
    while((read = bis.read(buffer, 0, buffer.length)) != -1) {
    bos.write(buffer, 0, buffer.length);
    }Your int 'read' holds the number of bytes read in but you then specify buffer.length in your write methods?!? why not use read? otherwise you will be writing the end of the buffer to your stream which contains random memory addresses. I think thats right anyway...
    Rob.

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

  • 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

  • Error message when trying create image from RAID

    I am trying to backup my RAID (697 GB) by creating an image (Disk Utility) on an external firewire drive. The settings are Read Only - I get an error message "image/device is too large"
    Is my RAID too large at 697GB to create an image?
    Thanks,
    Steven
      Mac OS X (10.4.3)  

    You have all 4 drives striped on the external drive?
    I'm not sure it will work -- an image may need to have 2x its actual size during creation. I'd have to check to be 100% sure.
    I think, though, it would be a lot better if you just did a pure "dupe," of the files from one volume onto another, rather than creating an image. It will be a ton easier.

Maybe you are looking for