This discussion is archived
0 Replies Latest reply: Dec 2, 2012 3:16 PM by 977494 RSS

upload image to php server using j2me

977494 Newbie
Currently Being Moderated
hi

i hope help me to solve this problem

I wrote code by j2me that can send image from mobile to a php page , which in turn are stored in the server ...

The problem appear when I want to display the image that was stored in the server , I received an error message that ""viewer can’t open this picture because the fi;e appears to be damaged"

It is noticeable that the size of the image in the server does not equal the size of the original image ...

can you help to solve this problem
the class as flow ...


import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
//import myProject.screens.SplashScreen;
public class SendImage extends MIDlet{
public String ti;
public String entrydate;
public String result;
private Display display;
public SendImage() {}
public void startApp() {
if(display == null){
display = Display.getDisplay(this);
}
     System.out.println("www");
display.setCurrent(new SplashScreen(this));
//display.setCurrent(null);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
}

/*****************************************/


import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import java.util.Hashtable;

//import myProject.ProjectMIDlet;

/**
* A simple splash screen.
*/
public class SplashScreen extends Canvas implements Runnable {

private Image mImage;
private SendImage projectMIDlet;
byte fileBytes[];

/**
* The constructor attempts to load the named image and begins a timeout
* thread. The splash screen can be dismissed with a key press,
* a pointer press, or a timeout
* @param projectMIDlet instance of MIDlet
*/
public SplashScreen(SendImage projectMIDlet){
this.projectMIDlet = projectMIDlet;
try{
mImage = Image.createImage("/badge.png");
//fileBytes=mImage.toString().getBytes();
fileBytes=ImageToByteArray.getByteArray(mImage);
//byte [] temp = mImage.toString().getBytes(); this also work
//System.out.println("\nto string"+b.length);
System.out.println("b"+fileBytes.length);

Thread t = new Thread(this);
t.start();
}
catch(IOException e){
               System.out.println("SendImage");
e.printStackTrace();
}
}

/**
* Paints the image centered on the screen.
*/
public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();

//set background color to overdraw what ever was previously displayed
g.setColor(0x000000);
g.fillRect(0,0, width, height);
g.drawImage(mImage, width / 2, height / 2,
Graphics.HCENTER | Graphics.VCENTER);
}

/**
* Dismisses the splash screen with a key press or a pointer press
*/
public void dismiss() {
//if (isShown())
// Display.getDisplay(projectMIDlet).setCurrent(new NextScreen(projectMIDlet));

try
{
//byte[] fileBytes = getFileBytes(); //retrieve file bytes with your own code
//ImageToByteArray.getByteArray(mImage);

Hashtable params = new Hashtable();
params.put("custom_param", "param_value");
params.put("custom_param2", "param_value2");
//HttpMultipartRequest req = new HttpMultipartRequest("http://localhost//uploadScript.php",params,"upload_field", "original_filename.png", "image/png", fileBytes);
HttpMultipartRequest req = new HttpMultipartRequest("http://localhost/uploadScrip.php",params,"upload_field", "badge.png", "image/png", fileBytes);

byte[] response = req.send();
System.out.println(new String(response));
          }
          catch(Exception e)
          {
                    System.out.println("dismiss");
     e.printStackTrace();
          }
}

/**
* Default timeout with thread
*/
public void run() {
try {
Thread.sleep(3000);//set for 3 seconds
}
catch (InterruptedException e) {
System.out.println("InterruptedException");
e.printStackTrace();
}
dismiss();
}

/**
* A key release event triggers the dismiss()
* method to be called.
*/
public void keyReleased(int keyCode) {
dismiss();
}

/**
* A pointer release event triggers the dismiss()
* method to be called.
*/
public void pointerReleased(int x, int y) {
dismiss();
}
}


/*****************************************/
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.lcdui.Image;

public class ImageToByteArray {

public static byte[] getByteArray(Image img) {
byte[] bytes = null;
int width = img.getWidth();
int height = img.getHeight();
int[] pixels = new int[width * height];
img.getRGB(pixels, 0, width, 0, 0, width, height);

try {
// convert int[] to byte[]
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
// I suggest writing these first: you'll need them to convert back
dout.writeInt(width);
dout.writeInt(height);
// then the pixels
for (int i = 0; i < pixels.length; i++) {
dout.writeInt(pixels);
}
bytes = bout.toByteArray();
} catch (IOException e) {
                    System.out.println("ImageToByteArray");
e.printStackTrace();
}

return bytes;
}
}

/*****************************************/

/***
*
* Copyright (C) 2008 Alessandro La Rosa
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: alessandro.larosa@gmail.com
*
* Author: Alessandro La Rosa
*/

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class HttpMultipartRequest
{
     static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";

     byte[] postBytes = null;
     String url = null;

     public HttpMultipartRequest(String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
     {
          this.url = url;

          String boundary = getBoundaryString();

          String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);

          String endBoundary = "\r\n--" + boundary + "--\r\n";

          ByteArrayOutputStream bos = new ByteArrayOutputStream();

          bos.write(boundaryMessage.getBytes());

          bos.write(fileBytes);

          bos.write(endBoundary.getBytes());

          this.postBytes = bos.toByteArray();

          bos.close();
     }

     String getBoundaryString()
     {
          return BOUNDARY;
     }

     String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
     {
          StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");

          Enumeration keys = params.keys();

          while(keys.hasMoreElements())
          {
               String key = (String)keys.nextElement();
               String value = (String)params.get(key);

               res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
                    .append("\r\n").append(value).append("\r\n")
                    .append("--").append(boundary).append("\r\n");
          }
          res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
               .append("Content-Type: ").append(fileType).append("\r\n\r\n");

          return res.toString();
     }

     public byte[] send() throws Exception
     {
          HttpConnection hc = null;

          InputStream is = null;

          ByteArrayOutputStream bos = new ByteArrayOutputStream();

          byte[] res = null;

          try
          {
               hc = (HttpConnection) Connector.open(url);

               hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());

               hc.setRequestMethod(HttpConnection.POST);

               OutputStream dout = hc.openOutputStream();

               dout.write(postBytes);

               dout.close();

               int ch;

               is = hc.openInputStream();

               while ((ch = is.read()) != -1)
               {
                    bos.write(ch);
               }
               res = bos.toByteArray();
          }
          catch(Exception e)
          {
               e.printStackTrace();
          }
          finally
          {
               try
               {
                    if(bos != null)
                         bos.close();

                    if(is != null)
                         is.close();

                    if(hc != null)
                         hc.close();
               }
               catch(Exception e2)
               {
                    e2.printStackTrace();
               }
          }
          return res;
     }
}


/*****************************************/

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points