Writing Image files from Applet to Servlet

How to write ImageFiles from an Applet to a Servlet?
I draw a image on a JComponent in Applet and wanted to save the image file in the server.
I am unable to write an Image Object to the Servlet as the BufferedImage class is not serialized.
I tried writing the image to the Servlet output stream and tried reading the data in the servlet and writing the data to a jpg file.
But the files is not being written as proper jpeg file.
Any help would be great.
Thanks,
Sridhar.

I get the following exception below when i try to write a Serialized object from an applet to the servlet.
I copied the serialized class jar file to the tomcat webserver lib folder.
The serialized class has a BufferedImage object.
Serialized Class Code
public class SerializedImage implements Serializable{
     private BufferedImage im = null;
     public SerializedImage() {
          super();
     public BufferedImage getSerializedObject() {
          return im;
     public void setSerializedObject((BufferedImage im) {
          this.im = im;
     private BufferedImage fromByteArray(byte[] imagebytes) {
          try {
               if (imagebytes != null && (imagebytes.length > 0)) {
                    BufferedImage im = ImageIO.read(new ByteArrayInputStream(imagebytes));
                    return im;
               return null;
          } catch (IOException e) {
               throw new IllegalArgumentException(e.toString());
     private byte[] toByteArray(BufferedImage o) {
          if(o != null) {
               BufferedImage image = (BufferedImage)o;
               ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
               try {
                    ImageIO.write(image, "jpg", baos);
               } catch (IOException e) {
                    throw new IllegalStateException(e.toString());
               byte[] b = baos.toByteArray();
               return b;
          return new byte[0];
     private void writeObject(java.io.ObjectOutputStream out)
     throws IOException {
          byte[] b = toByteArray(im);
          out.writeInt(b.length);
          out.write(b);
     private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException {
          int length = in.readInt();
          byte[] b = new byte[length];
          in.read(b);
          im = fromByteArray(b);
Exception :
java.io.StreamCorruptedException: unexpected block data
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1288)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:18
45)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1769)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1
646)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1274)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
Is there any thing that i am missing or doing wrong?
Thanks,
Sridhar.

Similar Messages

  • Loading PNG image file from Applet?

    Hi All,
    My applet running on IE6 and it will often loads 100 PNG image files from a webserver.
    Size of PNG file is about 60Kb so 100*60=6000 Kb ~ 6M.
    In theory, the applet will took 6M of memory to store all 100 files. In practical, it tooks about
    6M* 25 = 150M of memory, that make my applet run in out of memory sometimes.
    I know the reason, may be the brower/applet convert the PNG file format to BMP file format before showing on the screen.
    So the main point here is the applet should not loads all 100 files into the memory,
    it should loads only 10 files at the same time, another 90 files should be cached in memory as PNG file format, not BMP image file format to save the memory usage.
    Is this solution possible in applet field?
    If it is possible how can I implement it?
    And please show me better solution if anys.
    Many Thanks.

    I know the reason, may be the brower/applet convert the PNG file format to
    BMP file format before showing on the screen.This sounds VERY unlikely! Why should the browser do that? And the applet does what you have coded I hope!
    Your problem is probably somewhere else. And it has nothing to do with applets I presume. Use a heap analyzer tool to find out what hogs the memory. A thorough code review can't hurt either. If you still thinks it is the images though, then just don't load them all at once then.

  • Writing local files from applet

    Hi, I want to write an image file from an applet (appletviewer) to the local file system. Does anyone have any idea how I can do it? I tried using the FilePermission class but failed in doing so.
    Thanx for any help in advance

    I need to do this too.
    Specifically I need to allow the user of an applet to write (text) files to his own local file system.
    The applet displays graphical material to the user and I want the user to be able to type in comments to a text box which are then recorded by the applet - and ideally can be retrieved and used by the applet on subsequent occasions - as well as, of course, being available to the user via other programs.
    Presumably I need to use a signed applet.
    I want this to be as simple as possible so that the user (who will be unsophisticated) can be on Mac, Windows, Unix, Linux etc.
    Anyone know a good reference text or tutorial?
    (I am currently working with JAVA 2 fourth ed by Herbert Schildt)
    HRT

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    Applet:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    urlConnection.connect();
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    dout.close();
    urlConnection.disconnect();
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    try{
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    return false;
    }finally{
    if(f != null)f.close();
    Servlet:
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    System.out.println("c="+c);
    //ServletOutputStream servletoutputstream
    //response.getOutputStream();
    response.setContentType("application/octet-stream");
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    System.out.println("RemoteAddr:"+request.getRemoteAddr());
    System.out.println("RemoteHost:"+request.getRemoteHost());
    System.out.println("SessionID:"+request.getRequestedSessionId());
    System.out.println("Schema:"+request.getScheme());
    System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
    System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins = diss.read();
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    is.close();
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    try{
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = its.read()) != -1){
    f.write(buf, 0, byteLetti);
    f.flush();
    System.out.println("Byteletti="+byteLetti);
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    }finally{
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    myConnection.setUseCaches(false);
    myConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    myConnection.connect();
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    try
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
    *********************************************end***********************
    Thanks
    Joe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Uploading large files from applet to servlet throws out of memory error

    I have a java applet that needs to upload files from a client machine
    to a web server using a servlet. the problem i am having is that in
    the current scheme, files larger than 17-20MB throw an out of memory
    error. is there any way we can get around this problem? i will post
    the client and server side code for reference.
    Client Side Code:
    import java.io.*;
    import java.net.*;
    // this class is a client that enables transfer of files from client
    // to server. This client connects to a servlet running on the server
    // and transmits the file.
    public class fileTransferClient
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    // this method transfers the prescribed file to the server.
    // if the destination directory is "", it transfers the file to
    "d:\\".
    //11-21-02 Changes : This method now has a new parameter that
    references the item
    //that is being transferred in the import list.
    public static String transferFile(String srcFileName, String
    destFileName,
    String destDir, int itemID)
    if (destDir.equals(""))
    destDir = "E:\\FTP\\incoming\\";
    // get the fully qualified filename and the mere filename.
    String fqfn = srcFileName;
    String fname =
    fqfn.substring(fqfn.lastIndexOf(File.separator)+1);
    try
    //importTable importer = jbInit.getImportTable();
    // create the file to be uploaded and a connection to
    servlet.
    File fileToUpload = new File(fqfn);
    long fileSize = fileToUpload.length();
    // get last mod of this file.
    // The last mod is sent to the servlet as a header.
    long lastMod = fileToUpload.lastModified();
    String strLastMod = String.valueOf(lastMod);
    URL serverURL = new URL(webadminApplet.strServletURL);
    URLConnection serverCon = serverURL.openConnection();
    // a bunch of connection setup related things.
    serverCon.setDoInput(true);
    serverCon.setDoOutput(true);
    // Don't use a cached version of URL connection.
    serverCon.setUseCaches (false);
    serverCon.setDefaultUseCaches (false);
    // set headers and their values.
    serverCon.setRequestProperty("Content-Type",
    "application/octet-stream");
    serverCon.setRequestProperty("Content-Length",
    Long.toString(fileToUpload.length()));
    serverCon.setRequestProperty(FILENAME_HEADER, destDir +
    destFileName);
    serverCon.setRequestProperty(FILELASTMOD_HEADER, strLastMod);
    if (webadminApplet.DEBUG) System.out.println("Connection with
    FTP server established");
    // create file stream and write stream to write file data.
    FileInputStream fis = new FileInputStream(fileToUpload);
    OutputStream os = serverCon.getOutputStream();
    try
    // transfer the file in 4K chunks.
    byte[] buffer = new byte[4096];
    long byteCnt = 0;
    //long percent = 0;
    int newPercent = 0;
    int oldPercent = 0;
    while (true)
    int bytes = fis.read(buffer);
    byteCnt += bytes;
    //11-21-02 :
    //If itemID is greater than -1 this is an import file
    transfer
    //otherwise this is a header graphic file transfer.
    if (itemID > -1)
    newPercent = (int) ((double) byteCnt/ (double)
    fileSize * 100.0);
    int diff = newPercent - oldPercent;
    if (newPercent == 0 || diff >= 20)
    oldPercent = newPercent;
    jbInit.getImportTable().displayFileTransferStatus
    (itemID,
    newPercent);
    if (bytes < 0) break;
    os.write(buffer, 0, bytes);
    os.flush();
    if (webadminApplet.DEBUG) System.out.println("No of bytes
    sent: " + byteCnt);
    finally
    // close related streams.
    os.close();
    fis.close();
    if (webadminApplet.DEBUG) System.out.println("File
    Transmission complete");
    // find out what the servlet has got to say in response.
    BufferedReader reader = new BufferedReader(
    new
    InputStreamReader(serverCon.getInputStream()));
    try
    String line;
    while ((line = reader.readLine()) != null)
    if (webadminApplet.DEBUG) System.out.println(line);
    finally
    // close the reader stream from servlet.
    reader.close();
    } // end of the big try block.
    catch (Exception e)
    System.out.println("Exception during file transfer:\n" + e);
    e.printStackTrace();
    return("FTP failed. See Java Console for Errors.");
    } // end of catch block.
    return("File: " + fname + " successfully transferred.");
    } // end of method transferFile().
    } // end of class fileTransferClient
    Server side code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.net.*;
    // This servlet class acts as an FTP server to enable transfer of
    files
    // from client side.
    public class FtpServerServlet extends HttpServlet
    String ftpDir = "D:\\pub\\FTP\\";
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException,
    IOException
    doPost(req, resp);
    public void doPost(HttpServletRequest req, HttpServletResponse
    resp)
    throws ServletException,
    IOException
    // ### for now enable overwrite by default.
    boolean overwrite = true;
    // get the fileName for this transmission.
    String fileName = req.getHeader(FILENAME_HEADER);
    // also get the last mod of this file.
    String strLastMod = req.getHeader(FILELASTMOD_HEADER);
    String message = "Filename: " + fileName + " saved
    successfully.";
    int status = HttpServletResponse.SC_OK;
    System.out.println("fileName from client: " + fileName);
    // if filename is not specified, complain.
    if (fileName == null)
    message = "Filename not specified";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // open the file stream for the file about to be transferred.
    File uploadedFile = new File(fileName);
    // check if file already exists - and overwrite if necessary.
    if (uploadedFile.exists())
    if (overwrite)
    // delete the file.
    uploadedFile.delete();
    // ensure the directory is writable - and a new file may be
    created.
    if (!uploadedFile.createNewFile())
    message = "Unable to create file on server. FTP failed.";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // get the necessary streams for file creation.
    FileOutputStream fos = new FileOutputStream(uploadedFile);
    InputStream is = req.getInputStream();
    try
    // create a buffer. 4K!
    byte[] buffer = new byte[4096];
    // read from input stream and write to file stream.
    int byteCnt = 0;
    while (true)
    int bytes = is.read(buffer);
    if (bytes < 0) break;
    byteCnt += bytes;
    // System.out.println(buffer);
    fos.write(buffer, 0, bytes);
    // flush the stream.
    fos.flush();
    } // end of try block.
    finally
    is.close();
    fos.close();
    // set last mod date for this file.
    uploadedFile.setLastModified((new
    Long(strLastMod)).longValue());
    } // end of finally block.
    } // end - the new file may be created on server.
    } // end - we have a valid filename.
    // set response headers.
    resp.setContentType("text/plain");
    resp.setStatus(status);
    if (status != HttpServletResponse.SC_OK)
    getServletContext().log("ERROR: " + message);
    // get output stream.
    PrintWriter out = resp.getWriter();
    out.println(message);
    } // end of doPost().
    } // end of class FtpServerServlet

    OK - the problem you describe is definitely what's giving you grief.
    The workaround is to use a socket connection and send your own request headers, with the content length filled in. You may have to multi-part mime encode the stream on its way out as well (I'm not about that...).
    You can use the following:
    http://porsche.cis.udel.edu:8080/cis479/lectures/slides-04/slide-02.html
    on your server to get a feel for the format that the request headers need to take.
    - Kevin
    I get the out of Memory Error on the client side. I
    was told that this might be a bug in the URLConnection
    class implementation that basically it wont know the
    content length until all the data has been written to
    the output stream, so it uses an in memory buffer to
    store the data which basically causes memory issues..
    do you think there might be a workaround of any kind..
    or maybe a way that the buffer might be flushed after
    a certain size of file has been uploaded.. ?? do you
    have any ideas?

  • Problem in sending image from applet to servlet

    dear friends,
    i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
    i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
    i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
    at applet side
          jf.setContentPane(getJContentPane());
                     FileDialog fd=new FileDialog(jf,"hi");
                     fd.setMode(FileDialog.LOAD);
                     fd.setVisible(true);   
                     v=new Vector();
                     try{                                                
                               FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                               byte[] imgbuffer=new byte[fis.available()];
                               fis.read(imgbuffer);
                               ImageIcon imgdata=new ImageIcon(imgbuffer);
                               v.add(0,imgicon);
                                String strwp ="/UASProject/Storeimage";              
                                URL servletURL = new URL(getCodeBase(),strwp);             
                                HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                                servletCon.setDoInput(true); 
                                servletCon.setDoOutput(true);
                                servletCon.setUseCaches(false);
                                servletCon.setDefaultUseCaches(false);   
                                servletCon.setRequestMethod("POST");     
                                servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                                servletCon.connect();            
                                ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                                oboutStream.writeObject(v);
                                v.remove(0);
                                oboutStream.flush();      
                                oboutStream.close();  
                                //read back from servlet
                                ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                                 v= (Vector)inputStream.readObject();                     
                                 imgicon=(ImageIcon)v.get(1);
                                 showimg.setIcon(imgicon);
                                 this.getContentPane().validate();
                                 this.validate();  
                                inputStream.close();                                                        
                             //  repaint();
                     }catch(Exception e){e.printStackTrace();}  and this is at servlet side
            try {       
                         Vector v=new Vector();                    
                         ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                          v = (Vector)inputFromjsp.readObject();                                                                                                          
                          imgicon=(ImageIcon)v.get(0);                     
                          inputFromjsp.close();            
                          System.out.println(imgicon.getDescription());                                      
                          v.remove(0);
                          v.add(1,imgicon);
    //sending back to applet
                           response.setContentType("application/octet-stream");
                          ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
                          oboutstream.writeObject(v);
                          oboutstream.flush();
                          oboutstream.close();
                   } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
    thanks
    Edited by: san_4u on Nov 24, 2007 1:00 PM

    BalusC wrote:
    san_4u wrote:
    how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
    yeah! i got the related topic at http://www.theserverside.com/tt/articles/article.tss?l=HttpClient_FileUpload. please look it, i am reading it right now and expecting to be reliable for me.
    well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the servlet.is the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
    one mere question..
    i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
    now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
    because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
    hopes, you will have understand my quary, then please let me know the actual process
    thanks
    Edited by: san_4u on Nov 25, 2007 11:25 AM

  • How to display a dynamic image file from url?

    Hey,I want to display a dynamic image file from url in applet.For example,a jpg file which from one video camera server,store one frame pictur for ever.My java file looks like here:
    //PlayJpg.java:
    import java.awt.*;
    import java.applet.*;
    import java.net.*;
    public class PlayJpg extends Applet implements Runnable {
    public static void main(String args[]) {
    Frame F=new Frame("My Applet/Application Window");
    F.setSize(480, 240);
    PlayJpg A = new PlayJpg();
    F.add(A);
    A.start(); // Web browser calls start() automatically
    // A.init(); - we skip calling it this time
    // because it contains only Applet specific tasks.
    F.setVisible(true);
    Thread count = null;
    String urlStr = null;
    int sleepTime = 0;
    Image image = null;
    // called only for an applet - unless called explicitely by an appliaction
    public void init() {
                   sleepTime = Integer.parseInt(getParameter("refreshTime"));
              urlStr = getParameter("jpgFile");
    // called only for an applet - unless called explicitely by an appliaction
    public void start() {
    count=(new Thread(this));
    count.start();
    // called only for applet when the browser leaves the web page
    public void stop() {
    count=null;
    public void paint(Graphics g) {
    try{
    URL location=new URL(urlStr);
    image = getToolkit().getImage(location);
    }catch (MalformedURLException mue) {
                   showStatus (mue.toString());
              }catch(Exception e){
              System.out.println("Sorry. System Caught Exception in paint().");
              System.out.println("e.getMessage():" + e.getMessage());
              System.out.println("e.toString():" + e.toString());
              System.out.println("e.printStackTrace():" );
              e.printStackTrace();
    if (image!=null) g.drawImage(image,1,1,320,240,this);
    // called each time the display needs to be repainted
    public void run() {
    while (count==Thread.currentThread()) {
    try {
    Thread.currentThread().sleep(sleepTime*1000);
    } catch(Exception e) {}
    repaint(); // forces update of the screen
    // end of PlayJpg.java
    My Html file looks like here:
    <html>
    <applet code="PlayJpg.class" width=320 height=240>
    <param name=jpgFile value="http://Localhost/playjpg/snapshot0.jpg">
    <param name=refreshTime value="1">
    </applet>
    </html>
    I only get the first frame picture for ever by my html.But the jpg file is dynamic.
    Why?
    Can you help me?
    Thanks.
    Joe

    Hi,
    Add this line inside your run() method, right before your call to repaint():
    if (image != null) {image.flush();}Hope this helps,
    Kurt.

  • How to make a image file from Pre installed Mac osx ? "PLEASE HELP :("?

    hey guys ..Thanks u for the time.
    So i have this eMac which has crashed and i have got may hands on another eMac.. and it works
    ... the only problem is.. I can take my eMac to the working eMac to do Target Mode or any thing...
    So Help me..
    My question is .. Is there a way to make a .DMG image file from pre installed mac osx OR
    Is there a way to may a recovery disc??

    You can use Carbon Copy Cloner to copy everything from the working eMac onto the non-working eMac while the working eMac is running. If your eMac will still do target mode into the working one, you can download the above software, select the booted drive as the source drive, and your eMac's drive as the target, however it is possible this will not work.
    When you say your eMac crashed, what exactly happened?  It is possible that the hard drive in your eMac failed or is failing, so in order to get it running again you would need to replace the hard drive.  On the eMac, this repair is somewhat involved, and you have to be very careful because it exposes the CRT, which has several areas which can be extremely dangerous to touch if not properly handled.  CRTs retain a great deal of voltage, even when unplugged, sometimes for weeks, and they can give you a nasty shock if you touch them in the wrong place.
    Also keep in mind that cloning from the working computer to the non-working computer will ERASE any data that you have stored on that eMac, so if you don't have it backed up anywhere, you may want to attempt that with target mode before proceeding.
    Good luck!

  • How to Copy an Image File from a Folder to another Folder

    i face the problem of copying an image file from a folder to another folder by coding. i not really know which method to use so i need some reference about it. hope to get reply soon, thx :)

    Try this code. Make an object of this class and call
    copyTo method.
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class FileUtil
    extends File {
    public FileUtil(String pathname) throws
    NullPointerException {
    super(pathname);
    public void copyTo(File dest) throws Exception {
    File parent = dest.getParentFile();
    parent.mkdirs();
    FileInputStream in = new FileInputStream(this); //
    Open the source file
    FileOutputStream out = new FileOutputStream(dest); //
    Open the destination file
    byte[] buffer = new byte[4096]; // Create an input
    buffer
    int bytes_read;
    while ( (bytes_read = in.read(buffer)) != -1) { //
    Keep reading until the end
    out.write(buffer, 0, bytes_read);
    in.close(); // Close the file
    out.close(); // Close the file
    This is poor object-oriented design. Use derivation only when you have to override methods -- this is just
    a static utility method hiding here.

  • How use PHP to read image files from a folder and display them in Flex 3 tilelist.

    Hello. I need help on displaying images from a folder dynamically using PHP and display it on FLEX 3 TileList. Im currently able to read the image files from the folder but i don't know how to display them in the TileList. This is my current code
    PHP :
    PHP Code:
    <?php
    //Open images directory
    $imglist = '';
    $dir = dir("C:\Documents and Settings\april09mpsip\My Documents\Flex Builder 3\PHPTEST\src\Assets\images");
    //List files in images directory
    while (($file = $dir->read()) !== false)
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
    echo "filename: " . $file . "\n";
    $dir->close();
    ?>
    FLEX 3 :
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="pic.send();">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.events.FlexEvent;
    import mx.rpc.events.FaultEvent;
    import mx.events.ItemClickEvent;
    import mx.rpc.events.ResultEvent;
    public var image:Object;
    private function resultHandler(event:ResultEvent):void
    image = (event.result);
    ta1.text = String(event.result);
    private function faultHandler(event:FaultEvent):void
    ta1.text = "Fault Response from HTTPService call:\n ";
    ]]>
    </mx:Script>
    <mx:TileList x="31" y="22" initialize="init();" dataProvider = "{image}" width="630" height="149"/>
    <mx:String id="phpPicture">http://localhost/php/Picture.php</mx:String>
    <mx:HTTPService id="pic" url="{phpPicture}" method="POST"
    result="{resultHandler(event)}" fault="{faultHandler(event)}"/>
    <mx:TextArea x="136" y="325" width="182" height="221" id="ta1" editable="false"/>
    <mx:Label x="136" y="297" text="List of files in the folder" width="182" height="20" fontWeight="bold" fontSize="13"/>
    </mx:Application>
    Thanks. Need help as soon as possbile. URGENT.

    i have made some changes, in the php part too, and following is the resulting code( i tried it, and found that it works.):
    PHP Code:
    <?php
    echo '<?xml version="1.0" encoding="utf-8"?>';
    ?>
    <root>
    <images>
    <?php
    //Open images directory
    $dir = dir("images");
    //List files in images directory
    while (($file = $dir->read()) !== false)
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
    echo "<image>" . $file . "</image>"; // i expect you to use the relative path in $dir, not C:\..........
    //$dir->close();
    ?>
    </images>
    </root>
    Flex Code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute"
    creationComplete="callPHP();">
    <mx:Script>
    <![CDATA[
    import mx.rpc.http.HTTPService;
    import mx.controls.Alert;
    import mx.events.FlexEvent;
    import mx.rpc.events.FaultEvent;
    import mx.events.ItemClickEvent;
    import mx.collections.ArrayCollection;
    import mx.rpc.events.ResultEvent;
    [Bindable]
    private var arr:ArrayCollection = new ArrayCollection();
    private function callPHP():void
    var hs:HTTPService = new HTTPService();
    hs.url = 'Picture.php';
    hs.addEventListener( ResultEvent.RESULT, resultHandler );
    hs.addEventListener( FaultEvent.FAULT, faultHandler )
    hs.send();
    private function resultHandler( event:ResultEvent ):void
    arr = event.result.root.images.image as ArrayCollection;
    private function faultHandler( event:FaultEvent ):void
    Alert.show( "Fault Response from HTTPService call:\n " );
    ]]>
    </mx:Script>
    <mx:TileList id="tilelist"
    dataProvider="{arr}">
    <mx:itemRenderer>
    <mx:Component>
    <mx:Image source="images/{data}" />
    </mx:Component>
    </mx:itemRenderer>
    </mx:TileList>
    </mx:Application>

  • Playing an audio file from applet

    Hi friends,
    I have a problem to be solved .
    Please help me.
    I have to play an audio file from applet.When the applet loads it shold start playing .There is a progress bar in the applet it shold alsomove corresponding to that.
    How can i do that.Give me an idea.
    I know nothing about jmf.
    I am using j2sdk1.4,windows 2000 server.

    Andrew,
    Forgive my naivety, but i struggle with JAVA! I am desperately trying to create a JAVA plugin to SERVOY and have to date been successful with a few things. Record, Playback, convert to .spx.
    I am really struggling with implementing a rewind and fastforward function of the type you have. I thought it would be easy, but it appears not.
    At the bottom is the complete code from my class that is called by the servoy plugin wrapper,
    i had thought that adding some simple jump 500 ms would have been easy in something like this:
    public AudioStream js_FastForward (AudioStream as) throws IOException {
    !!! Line or two here to move the play head forward !!!
         AudioPlayer.player.start(as);
         return as;
    Can you give me any pointers to how i code that fast forward bit.
    many thanks
    David
    package com.d2e.MyPlugin;
    import com.servoy.j2db.scripting.IScriptObject;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.Button;
    import javax.sound.sampled.*;
    import org.xiph.speex.*;
    import org.xiph.speex.spi.*;
    import  sun.audio.*;    //import the sun.audio package
    public class MyPluginProvider implements IScriptObject  {
          public void JSencode()
             throws IOException{
               /** Version of the Speex Encoder */
                final String VERSION = "Java Speex Command Line Encoder v0.9.7 ($Revision: 1.5 $)";
                /** Copyright display String */
                final String COPYRIGHT = "Copyright (C) 2002-2004 Wimba S.A.";
                /** Print level for messages : Print debug information */
                final int DEBUG = 0;
                /** Print level for messages : Print basic information */
                final int INFO  = 1;
                /** Print level for messages : Print only warnings and errors */
                final int WARN  = 2;
                /** Print level for messages : Print only errors */
                final int ERROR = 3;
                int printlevel = INFO;
                /** File format for input or output audio file: Raw */
                final int FILE_FORMAT_RAW  = 0;
                /** File format for input or output audio file: Ogg */
                final int FILE_FORMAT_OGG  = 1;
                /** File format for input or output audio file: Wave */
                final int FILE_FORMAT_WAVE = 2;
                int srcFormat  = FILE_FORMAT_OGG;
                int destFormat = FILE_FORMAT_WAVE;
                int mode       = -1;
                int quality    = 4;
                /** Defines the encoders algorithmic complexity. */
                 int complexity = 3;
                /** Defines the number of frames per speex packet. */
                 int nframes    = 1;
                /** Defines the desired bitrate for the encoded audio. */
                 int bitrate    = -1;
                /** Defines the sampling rate of the audio input. */
                 int sampleRate = -1;
                /** Defines the number of channels of the audio input (1=mono, 2=stereo). */
                 int channels   = 1;
                /** Defines the encoder VBR quality setting (float from 0 to 10). */
                 float vbr_quality = -1;
                /** Defines whether or not to use VBR (Variable Bit Rate). */
                 boolean vbr    = false;
                /** Defines whether or not to use VAD (Voice Activity Detection). */
                 boolean vad    = false;
                /** Defines whether or not to use DTX (Discontinuous Transmission). */
                 boolean dtx    = false;
              //HArd code src format and dest
               // private String srcPath ="junk.wav";
              srcFormat = FILE_FORMAT_WAVE;
              destFormat = FILE_FORMAT_OGG;
              //destPath="junk.spx";
             byte[] temp    = new byte[2560]; // stereo UWB requires one to read 2560b
             final int HEADERSIZE = 8;
             final String RIFF      = "RIFF";
             final String WAVE      = "WAVE";
             final String FORMAT    = "fmt ";
             final String DATA      = "data";
             final int WAVE_FORMAT_PCM = 0x0001;
             // Open the input stream
             DataInputStream dis = new DataInputStream(new FileInputStream("junk.wav"));
             // Prepare input stream
           //DP - Sort out the Wave File
               // read the WAVE header
               dis.readFully(temp, 0, HEADERSIZE+4);
               // Read other header chunks
               dis.readFully(temp, 0, HEADERSIZE);
               String chunk = new String(temp, 0, 4);
               int size = readInt(temp, 4);
               while (!chunk.equals(DATA)) {
                 dis.readFully(temp, 0, size);
                 if (chunk.equals(FORMAT)) {
                   typedef struct waveformat_extended_tag {
                   WORD wFormatTag; // format type
                   WORD nChannels; // number of channels (i.e. mono, stereo...)
                   DWORD nSamplesPerSec; // sample rate
                   DWORD nAvgBytesPerSec; // for buffer estimation
                   WORD nBlockAlign; // block size of data
                   WORD wBitsPerSample; // Number of bits per sample of mono data
                   WORD cbSize; // The count in bytes of the extra size
                   } WAVEFORMATEX;
                   if (readShort(temp, 0) != WAVE_FORMAT_PCM) {
                     System.err.println("Not a PCM file");
                     return;
                   channels = readShort(temp, 2);
                   sampleRate = readInt(temp, 4);
                   if (readShort(temp, 14) != 16) {
                     System.err.println("Not a 16 bit file " + readShort(temp, 18));
                     return;
                   // Display audio info
                   if (printlevel <= DEBUG) {
                     System.out.println("File Format: PCM wave");
                     System.out.println("Sample Rate: " + sampleRate);
                     System.out.println("Channels: " + channels);
                 dis.readFully(temp, 0, HEADERSIZE);
                 chunk = new String(temp, 0, 4);
                 size = readInt(temp, 4);
               if (printlevel <= DEBUG) System.out.println("Data size: " + size);
           //DP ENd sort wave file 
           //Now Choose the mode , we have a file sampled at 44100
                 mode = 2; // Ultra-wideband
             // Construct a new encoder
             SpeexEncoder speexEncoder = new SpeexEncoder();
             speexEncoder.init(mode, quality, sampleRate, channels);
             if (complexity > 0) {
               speexEncoder.getEncoder().setComplexity(complexity);
             if (bitrate > 0) {
               speexEncoder.getEncoder().setBitRate(bitrate);
             if (vbr) {
               speexEncoder.getEncoder().setVbr(vbr);
               if (vbr_quality > 0) {
                 speexEncoder.getEncoder().setVbrQuality(vbr_quality);
             if (vad) {
               speexEncoder.getEncoder().setVad(vad);
             if (dtx) {
               speexEncoder.getEncoder().setDtx(dtx);
             // Display info
             // Open the file writer
             AudioFileWriter writer;
             if (destFormat == FILE_FORMAT_OGG) {
               writer = new OggSpeexWriter(mode, sampleRate, channels, nframes, vbr);
             else if (destFormat == FILE_FORMAT_WAVE) {
               nframes = PcmWaveWriter.WAVE_FRAME_SIZES[mode-1][channels-1][quality];
               writer = new PcmWaveWriter(mode, quality, sampleRate, channels, nframes, vbr);
             else {
               writer = new RawWriter();
             writer.open("junk.spx");
             writer.writeHeader("Encoded with: " + VERSION);
             int pcmPacketSize = 2 * channels * speexEncoder.getFrameSize();
             try {
               // read until we get to EOF
               while (true) {
                 dis.readFully(temp, 0, nframes*pcmPacketSize);
                 for (int i=0; i<nframes; i++)
                   speexEncoder.processData(temp, i*pcmPacketSize, pcmPacketSize);
                 int encsize = speexEncoder.getProcessedData(temp, 0);
                 if (encsize > 0) {
                   writer.writePacket(temp, 0, encsize);
             catch (EOFException e) {}
             writer.close();
             dis.close();
            * Converts Little Endian (Windows) bytes to an int (Java uses Big Endian).
            * @param data the data to read.
            * @param offset the offset from which to start reading.
            * @return the integer value of the reassembled bytes.
           protected static int readInt(final byte[] data, final int offset)
             return (data[offset] & 0xff) |
                    ((data[offset+1] & 0xff) <<  8) |
                    ((data[offset+2] & 0xff) << 16) |
                    (data[offset+3] << 24); // no 0xff on the last one to keep the sign
            * Converts Little Endian (Windows) bytes to an short (Java uses Big Endian).
            * @param data the data to read.
            * @param offset the offset from which to start reading.
            * @return the integer value of the reassembled bytes.
           protected static int readShort(final byte[] data, final int offset)
             return (data[offset] & 0xff) |
                    (data[offset+1] << 8); // no 0xff on the last one to keep the sign
         AudioFormat audioFormat;
           TargetDataLine targetDataLine;
         public Class[] getAllReturnedTypes() {
              // TODO Auto-generated method stub
              return null;
         public String[] getParameterNames(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public String getSample(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public String getToolTip(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public boolean isDeprecated(String arg0) {
              // TODO Auto-generated method stub
              return false;
         public String js_Record (String name){
              captureAudio();
              return "Started Recording " +name;
        public String js_StopRecord (String name) throws IOException{
             //new ActionListener(){
             //   public void actionPerformed(ActionEvent e)
                  //Terminate the capturing of input data
                  // from the microphone.
                  targetDataLine.stop();
                  targetDataLine.close();
              //  }//end actionPerformed
             //};//end ActionListener
                 // JSpeexEnc ("junk.wav","output.spx");
                  JSencode();
              return "Stop Records " +name;
        //Play audio file
        public AudioStream js_Playback (String name) throws IOException{
             InputStream in = new FileInputStream("junk.wav");
             AudioStream as = new AudioStream(in);        
             AudioPlayer.player.start(as);           
             return as;
        public AudioStream js_ContPlay (AudioStream as) throws IOException {
             AudioPlayer.player.start(as);           
             return as;
         //Stop Play
        public AudioStream js_Stop_Playback (AudioStream as) throws IOException{
             AudioPlayer.player.stop(as);
              return as;
         //This method captures audio input from a
        // microphone and saves it in an audio file.
        private void captureAudio(){
          try{
            //Get things set up for capture
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo =
                                new DataLine.Info(
                                  TargetDataLine.class,
                                  audioFormat);
            targetDataLine = (TargetDataLine)
                     AudioSystem.getLine(dataLineInfo);
            //Create a thread to capture the microphone
            // data into an audio file and start the
            // thread running.  It will run until the
            // Stop button is clicked.  This method
            // will return after starting the thread.
            new CaptureThread().start();
          }catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
          }//end catch
        }//end captureAudio method  
    //  This method creates and returns an
        // AudioFormat object for a given set of format
        // parameters.  If these parameters don't work
        // well for you, try some of the other
        // allowable parameter values, which are shown
        // in comments following the declarations.
        private AudioFormat getAudioFormat(){
          float sampleRate = 44100.0F;
          //8000,11025,16000,22050,44100
          int sampleSizeInBits = 16;
          //8,16
          int channels = 1;
          //1,2
          boolean signed = true;
          //true,false
          boolean bigEndian = true;
          //true,false
          return new AudioFormat(sampleRate,
                                 sampleSizeInBits,
                                 channels,
                                 signed,
                                 bigEndian);
        }//end getAudioFormat
        class CaptureThread extends Thread{
               public void run(){
                 AudioFileFormat.Type fileType = null;
                 File audioFile = null;
                 //Set the file type and the file extension
                 // based on the selected radio button.
                 //if(aifcBtn.isSelected()){
                  // fileType = AudioFileFormat.Type.AIFC;
                  // audioFile = new File("junk.aifc");
                // }else if(aiffBtn.isSelected()){
                 //  fileType = AudioFileFormat.Type.AIFF;
                 //  audioFile = new File("junk.aif");
                // }else if(auBtn.isSelected()){
                 //  fileType = AudioFileFormat.Type.AU;
                 //  audioFile = new File("junk.au");
                // }else if(sndBtn.isSelected()){
                //   fileType = AudioFileFormat.Type.SND;
                 //  audioFile = new File("junk.snd");
                // }else if(waveBtn.isSelected()){
                 fileType = AudioFileFormat.Type.WAVE;
                 audioFile = new File("junk.wav");
                // }//end if
                 try{
                   targetDataLine.open(audioFormat);
                   targetDataLine.start();
                   AudioSystem.write(
                         new AudioInputStream(targetDataLine),
                         fileType,
                         audioFile);
                 }catch (Exception e){
                   e.printStackTrace();
                 }//end catch
               }//end run
             }//end inner class CaptureThread
    }

  • How to Insert image file from fileChooser to a tabbedPane?

    Hi,
    Currently, i have encounted a problem halfway through my project. That is how do i insert images into a tabbedPane after selecting a image file from the fileChooser?
    Do anyone has any idea of how to solve the above problem?
    Thanks!!

    I would put the image in a JLabel and put the JLabel in the tabbed pane.

  • Drag image file from Windows Explorer to a new layer in an open file

    I want to know if it's possible in CS3 to drag an image file from Windows Explorer into an already open file in PS.  Right now when I drag over, it opens that file.  I want to have it where the image is inserted as a new layer into the existing open file.  is that possible?

    Hi, I'm using CS4 and would love to be able to drag n drop straight to a new layer in an existing file.
    At present when I drag n drop I get a new image in PS. I then have to move this to my existing image. I have tried draging to the tab, the layer box, the image, the blank space, using shift,ctrl & alt.
    A simple how to would be nice

  • Cannot unzip the image file from Sun

    I have downloaded the first compressed install CD image file from Sun. But it cannot be unzip. I used almost all of the unzip software(such as Winzip, WinRAR, PKUNZIP for DOS and for Windows).
    Anybody can help me?

    OK! I downloaded for the 5th time without using GetRight and I can now unzip the file in question. For some reason GetRight chokes on this zip file only. All of the other images were downloaded using GetRight and they unzipped just fine. Go figure...
    My reccomendation to anyone else using a download tool like GetRight and having the same problem is to disabled the tool temporarily and just do a normal download through your browser.
    Hope someone finds this useful.
    Bob C.
    Make that another ditto!!! I have downloaded the
    first CD image for x86 Solaris 4 times now. Each time
    the download has succeeded without error, but I can
    not open the zip file. I have been using GetRight 4.3
    to do the download rather than straight FTP or HTTP so
    maybe this is the issue, but I have never had a
    problem using this tool before.
    Help anyone!?!?!?!
    Bob C

  • I can not open raw image files from my Cannon 5d mark iii with cs6 and my cs6 in mac

    I can not open raw image files from my Cannon 5d mark iii with cs6 and my cs6 in mac

    The Mk III requires an updated version of Camera RAw, so run Help --> Updates and install it.
    Mylenium

Maybe you are looking for