Reading and Writing Image through Socket

hi
i'm doing a mobileapplication and i send the Image from the server using a DataOutputStream. I'm converting the Image to a byteArray. The Image in .png format. But i need to read it from a J2ME application and when i read the byteArray and convert it to a Image it gives a illegalArgumentException coz it says that cannot decode the Image.
Can anyone Help
Rushi

some png files are not standard png files thats why u may get the error but u should try like this:
Server side=>
OutputStream os=c.getOutputStream();
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
os.write(buf, 0, numBytesRead);
Client side=>
bStrm=new ByteArrayOutputStream();
c = 0;
while ((c=dis.read())!=-1)
bStrm.write(c);
imgData = bStrm.toByteArray();
bStrm.close();
img=Image.createImage(imgData,0,imgData.length);

Similar Messages

  • Having trouble listening and writing to a socket

    I might as well just post my classes. What I really need is a comprehensive guide to reading and writing to a socket. The sockets aren't being printed, and I know it's because they hang on the "readline()" statements in the netcheck functions. Why do they hang?
    ===================================================================
    package TerminalChat;
    import java.io.*;
    import java.net.*;
    public class QOTDServer {
         private ServerSocket serversock;
         private Socket spawnsock;
         public QOTDServer()
              // Establishes a new server socket on port 5005
              try
                   serversock = new ServerSocket(5005);
              catch (IOException e01)
                   System.out.println("Error: " + e01);
                   System.out.println("server socket establishment stage error");
              // Untill the program is closed it will always wait untill the "ServerSocket" is accepted.
              // Once accepted, it will create a "Socket".
              while(true)
                        try
                             System.out.println("Before connect");
                             spawnsock = serversock.accept();
                             System.out.println("After connect");
                             new Thread(new ConnectionSpawn(spawnsock)).start();
                        catch(IOException e02)
                             System.out.println("Error: " + e02);
                             System.out.println("socket accept stage error");
         public static void main(String[] args)
              // TODO Auto-generated method stub
              new QOTDServer();
    ===================================================================
    package TerminalChat;
    import java.io.*;
    import java.net.*;
    public class ConnectionSpawn implements Runnable {
         Socket connSpawnSocket;
         BufferedWriter buffwrite;
         BufferedReader buffread;
         public ConnectionSpawn(Socket sock)
              connSpawnSocket = sock;
         public void run()
              try
                   buffread = new BufferedReader(new InputStreamReader(connSpawnSocket.getInputStream()));
                   buffwrite = new BufferedWriter(new OutputStreamWriter(connSpawnSocket.getOutputStream()));
              catch(IOException e01)
                   System.out.println("Error: " + e01);
                   System.out.println("bufferedread/bufferedwrite reference to member stage error");
              this.broadcast("hello Client");
              System.out.println("Testclient: " + netcheck());
         public String netcheck()
              String msg = "No messages";
              try
                   msg = buffread.readLine();
                   System.out.println("post readline check");
              catch(IOException e02)
                   System.out.println("Error: " + e02);
                   System.out.println("netcheck stage error");
              return msg;
         public void broadcast(String message)
              try
                   buffwrite.write(message);
              catch(IOException e03)
                   System.out.println("Error: " + e03);
                   System.out.println("ConnectionSpawn write error stage error will this make it to the terminal?");
    ===================================================================
    package TerminalChat;
    import java.net.*;
    import java.io.*;
    public class Client {
         Socket clientSocket;
         BufferedWriter buffwrite;
         BufferedReader buffread;
         public Client()
              try
                   clientSocket = new Socket("127.0.0.1", 5005);
              catch(Exception e01){}
              try
                   buffread = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   buffwrite = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
              catch (Exception e02)
                   System.out.println("Error: " + e02);
                   System.out.println("bufferedread/bufferedwrite reference to member stage error");
              this.broadcast("Hello Server");
              System.out.println("Testclient: " + netcheck());
         public String netcheck()
              String msg = "No messages";
              try
                   msg = buffread.readLine();
                   System.out.println("post readline check");
              catch(IOException e02)
                   System.out.println("Error: " + e02);
                   System.out.println("netcheck stage error");
              return msg;
         public void broadcast(String message)
              try
                   buffwrite.write(message);
              catch(IOException e03)
                   System.out.println("Error: " + e03);
                   System.out.println("broadcast check error");
         public static void main(String[] args)
              // TODO Auto-generated method stub
              new Client();
    }

    Oh yea, I just forgot to flush :)
    Everything's fine now - works great. BTW, do you guys
    reccomend keeping a socket, or just creating a new
    one every time you want to send information?Now why would you want to create a new Socket everytime.From the server once a Sockets bounds to the port you stick by it receive the desired clients.From the client side once a socket establishes a connection with the other host you can keep that socket alive till you carry out the task that you want to and then once you are through close the connection.

  • IPhone4 how through the USB mobile phone file reading and writing?

    iPhone4 how through the USB mobile phone file reading and writing?

    No idea what you are asking.
    Please explain

  • ImageIo: reading and writing a jpeg corrupts the image

    Sometimes, ImageIo manages to read an image wrong. If I simply read() and write() the
    image without any transformations, the image writtten will have its colors all wrong. The
    output image format here doesn't matter.
    An example image is: http://bram.name/~brama/pics/test.jpg
    And output after reading and writing it: http://bram.name/~brama/pics/test_output.jpg
    Is the image io lib to blame, or is it a broken image? The image displays fine in other programs.
    Message was edited by:
    Bram_A

    Use this code to load the image.
    From my experience it is much more stable and also faster.
    My guess is that the problem is related to the ICC profile embeded in the JPEG.
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new URL("http://www.stack.nl/~brama/pics/imageio.jpg").openStream());
    BufferedImage image = decoder.decodeAsBufferedImage();

  • Switcher - Reading and Writing External IEEE HDD's

    Greetings,
    i'm trying to read and write with my external ieee drive on windows and the mac pro. it's format is ntfs, and is read only on the mac pro.
    i am admin and can't seem to change the permissions to read / write.
    the over all idea is i need to go back and forth between operating systems reading and writing from both sides of the house.
    here's a snapshot.
    http://briankross.com/images/500GBIEEEHDD.jpg
    Mac Pro   Mac OS X (10.4.8)  

    Unfortunately, no. In order to convert the drive to FAT32 it must be re-partitioned which is a destructive process.
    Why reward points?(Quoted from Discussions Terms of Use.)
    The reward system helps to increase community participation. When a community member gives you (or another member) a reward for providing helpful advice or a solution to their question, your accumulated points will increase your status level within the community.
    Members may reward you with 5 points if they deem that your reply is helpful and 10 points if you post a solution to their issue. Likewise, when you mark a reply as Helpful or Solved in your own created topic, you will be awarding the respondent with the same point values.

  • Send a image through socket method getoutputstream

    cani send an image through socket methods instead of send a txt

    1) Use the search feature, or look back a couple of pages, this question was asked sometime yesterday
    2) In all the many times that it's been asked, no-one denies it but at the same time no-one's posted any code to do it (AFAIK) I'd be interested too if anyone does find a way...

  • Reading and writing a ByteArray

    This question was posted in response to the following article: http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118666ade46-7d54.html

    I believe that the example of Reading and Writing Objects needs a rewrite
    First, the attempt to use comments to interleave a Flex-ified example with a Flash example of the uses of the ByteArray Class is a shortcut that ultimately fails.  Take the time to create two, separately valid examples for the two different frameworks.
    Second, the interlinea comments show a rather poor example of how to write clean code, and are entirely confusing to the person you you trying to help learn how to use your library.  Look at the declaration of a variable called outFile:File, a comment about some function that is to be declared somewhere with the same name, outFile(), and indeed, if this code were to compile -- which I am sure it could not -- the compiler would see that you try to invoke an outFile() function.  No one gets through an interview who writes code that way.
    Third, I am not sure you understand how the readBytes and writeBytes methods work. In the upper example, where an order is being written to the file system, the writeBytes method uses data.length correctly.  At the point in time that it is used, the XML object will have been written into the bytes:ByteArray, so it will have a proper length.
    On the other hand, in the second half of the example, where the readBytes method similarly passes data.length, the reader has to be very lucky to note that at that point in time data.length will have a value of zero.  The inBytes:ByteArray was only instantiated, not populated with anything, as, indeed it should not be, at that point in the logic flow.  Most importantly, when the program does need to readBytes, there is no way for the program to know in advance what the length of the byte stream coming in from the file system will be.  Your example would be more correct, and could make a useful point in showing that readBytes (data) is the correct way to pass the arguments because the default behavior will then be used and the default behavior will be to make data whatever length it needs to be in order to hold the content from the file system.  The program can know the value of data.length after the read has taken place, but not before.

  • Problem on reading and writing from from a *.txt file

    I get Problem on reading and writing from from a *.txt file. The following is the read() method...
    The software said the DataInputStream is depreciated. Can anyone help me please?
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        String str = "";
        try
          in = new BufferedReader(file);
          //in = new FileInputStream(file);
          for(;;)
            str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);
      }

    Thank you for your reply. I have made some change. However, there is an incompetable type found error.
    in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        //BufferedReader in = null;
        String str = "";
        try
          in = new BufferedReader(new InputStreamReader(in));
          //in = new FileInputStream(file);
          for(;;)
            BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
            //str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);

  • File importer detected an inconsistency in the file stucture of (file name). Reading and writing this file's metadata (XMP) has been disabled.

    I have duplicated a project to work on another computer. The project opens fine but when I import new footage/audio files I get this message. "File importer detected an inconsistency in the file stucture of (file name). Reading and writing this file's metadata (XMP) has been disabled." Then I can't play my timeline and Premier Pro crashes.  I have to force quit and restart my computer to continue working. What does this error really mean? How do you rectify?
    Our workflow requires that we duplicate projects to make updates because we are frequently revising but need to keep original project unchanged and intact.

    I have a similar issue and message , but occurs when I import AVI clips from OnLocation CS4 to Premier Pro CS4.

  • I updated Itunes today to the latest version. Windows 7 64bit. None of my drivers work and get an error when itunes starts, about registry setting for reading and writing dvds and cds missing. Anyone else have the same issue. I downloaded itunes again, re

    I updated Itunes today to the latest version. Windows 7 64bit. None of my drivers work and get an error when itunes starts, about registry setting for reading and writing dvds and cds missing. Anyone else have the same issue. I downloaded itunes again, reinstalled still have same issue.

    I'd start with the following document, with one modification. At step 12 after typing GEARAspiWDM press the Enter/Return key once prior to clicking OK. (Pressing Return adds a carriage return in the field and is important.)
    iTunes for Windows: "Registry settings" warning when opening iTunes

  • How to read and input Chinese through Blackberry wireless cell phone

    The way to read and input Chinese through Blackberry wireless cell phone
    My phone model  is Blackberry 8520.
    My Blackberry can read and input Chinese after these steps. 
    1. Go to the weblink http://na.blackberry.com/eng/support/downloads/download_sites.jsp
    2. Click "China Mobile Peoples Telephone" included in "Asia Pacific".
    3.Select a product from the drop down menu, for example, mine is BlackBerry 8520, and I select it.
    4.Click "next"
    5.Then select the "Download Software" on thebottom of the same webpage.
    6.Fill in all the information required on the following page, then "Next"
    7. Start download the software to you PC, computer or laptop.
    8.Install this downloaded software to your PC. The software is called "8520wifijEastAsia_PBr4.6.1_rel424_PL4.2.0.122_A4.6.1.286_China_Mobile_Hong_Kong_Co._Ltd"
    9.Link your wireless cell phone to your PC
    10.Then go to C:\Program Files\Common Files\Research In Motion\AppLoader
    11. Double click "Loader"
    12. Select all the languages you want to update to your cell, and then follow the information to the left steps.
    It will take about 20 minutes after Step 12 to finish the upload to the cell.
    Done.
    Now I am happy I can read and input both English and Chinese through my BlackBerry.
    If you have any questions, please leave message to me on this web.
    Good luck.
    Grace

    Hi Grace,
    I'd faced the same issue as KU.
    After all the installation.. it does not have any options for me to choose for the language.. can kindly assist me on this???
    it only showed those applications that i had in my mobile...
    Thanks
    -fei-

  • Reading and Writing large Excel file using JExcel API

    hi,
    I am using JExcelAPI for reading and writing excel file. My problem is when I read file with 10000 records and 95 columns (file size about 14MB), I got out of memory error and application is crashed. Can anyone tell me is there any way that I can read large file using JExcelAPI throug streams or in any other way. Jakarta POI is also showing this behaviour.
    Thanks and advance

    Sorry when out of memory error is occurred no stack trace is printed as application is crashed. But I will quote some lines taken from JProfiler where this problem is occurred:
              reader = new FileInputStream(new File(filePath));
              workbook = Workbook.getWorkbook(reader);
              *sheeet = workbook.getSheet(0);* // here out of memory error is occured
               JProfiler tree:
    jxl.Workbook.getWorkBook
          jxl.read.biff.File 
                 jxl.read.biff.CompoundFile.getStream
                       jxl.read.biff.CompoundFile.getBigBlockStream Thanks

  • Quickest method for reading and writing files

    Hi
    I need help regarding file operations.(Reading and Writing). Currently I am using BufferedReader and BufferedWriter to read and write files. But the files (XML) are very huge files(from 30 -50 mb). This is slowing the application to a great extent. Is there any other approach to perform the above mentioned operations on XML files in a fast manner.
    Thank You
    Mansoor.

    Hi
    Can u let me know how to use the java.nio pavkage for primitve data types(int,float..., boolean). I have tried it but found no success.
    Thank You
    Mansoor

  • Lightweight library for reading and writing mp3-tags

    Hi,
    I'm currently evaluating libraries for reading and writing mp3-tags. All the projects I found so far where not maintained for a couple of years.
    My question:
    Is there currently a library, which one could call standard for this purpose
    Cheers
    Jonny

    jonnybecker wrote:
    I'm currently evaluating libraries for reading and writing mp3-tags. Don't you rather mean ID3 tags?
    All the projects I found so far where not maintained for a couple of years.It may either be dead, or it may be so finished and free of bugs that no maintenance is needed anymore.
    If you're occurring problems with it and if it is open source you can always consider taking a fork for own development.
    Is there currently a library, which one could call standard for this purposeNo one comes to mind.

  • Very slow painting while reading and writing doubles into file

    for 15MB length file i = 7662080
    for 50MB length file i = 12414368
    Part of Code for writing into file follows like this:
    try{
    fos = new FileOutputStream("Angel.txt");
    File f = new File("Angel.txt");
         if(f.length() >=4)
         f.delete();
    fos = new FileOutputStream("Angel.txt");     
    dos = new DataOutputStream(new BufferedOutputStream(fos,1000000));
    int x=0;
    double y_last, y_new;
    for(int j=0 ;j<i ;j++)
    if(some condition)
    y_new = ....;
    try{
    //previously in vectors
    y_last = y_new;
    vect.add(new Line2D.Double(x, y_last, x, y_new)_;
    dos.writeDouble(y_new);
         }catch(Exception e){System.out.println(e);}
    dos.close();
    fos.close();
    x++;
    }catch(Exception excp){System.out.println(excp);}
    part of code for reading from file follows like this:
    public void paint(Graphics g)
    try{
         double y1, y2 =0;               
         Line2D.Double doub;
         raf = new RandomAccessFile("Angel.txt","r");
         dis = new DataInputStream(new BufferedInputStream(new FileInputStream(raf.getFD(),1000000)));
         raf.seek((rect.x*8));
         for (int i = 0/any value; (i < value as per choice); i++)
              g2.setStroke(new BasicStroke(0)); //2
              y1 = y2;
         y2 =dis.readDouble();
              doub=new Line2D.Double(i,y1,i,y2);
              g2.draw(doub);
    dis.close();
         raf.close();
    }catch(Exception excp){System.out.println(excp);}
    I tried using Object Streams but NotSerializable Exception is thrown as Line2D.Double objects
    are not serialized.
    Any idea to make reading and writing into file specially from MB files faster is appreciated.

    Why are you reading in the file in the paint method ?
    Create your data once before painting.
    I think you should explain what is your goal and what behavior you want.
    Denis

Maybe you are looking for

  • IPod touch no longer playing on Sony dream machine after updating iOS

    Can not get my daughters iPod touch 4th gen to play on Sony dream machine after updating the iOS to 6.1.3. Looking for suggestions on how to fix this?!

  • Labels printing : "unable to read format"

    Hello I have configured a Printronix Label printer as a network printer (Acess Method U). Communication test is successfull But when I execute a printout I have the following message: ========================= Print request processing log Errors occu

  • No pass word, no Flash Player

    Safari 6.04, Flash Player 11 downloaded, OS 10.8.3, MacBook Pro 2009. New HD 160 GB after HD crash. Forgot my pass word, creating new pass word did not help. Flash Player on iPhone is all right. Is it possible to copy data from iPhone to MacBook Pro?

  • Max number of queries in webi

    Hi all Someone know what is the maximum number of queries in a Web Intelligence document with Java Panel Reports? Thanks for your help.

  • Java-pdf-xml

    i have to convert pdf file to xml. i have to write code to extract the content from pdf file. i want functions or api's for extracting text from pdf pls help me