很抱歉,在J2ME平台发送图片到servlet那篇文章中,我忽略了一个细节没有进行数据类型的转换。这样会导致图片像素的损失,发送到服务器的图片失真。现在将代码重新更新一下,给大家带来不便还请原谅。
public synchronized void connHttp(){
while(true){
System.out.println("httpconn wait now");
if((midplet.getIsSending())){
System.out.println("search");
try{
con=(HttpConnection)Connector.open(URL);
con.setRequestMethod(HttpConnection.POST);
con.setRequestProperty("If-Modified-Since",
"29 Oct 1999 19:43:31 GMT");
con.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.0");
con.setRequestProperty("Content-Language", "en-US");
os=new DataOutputStream(con.openOutputStream());
int[] rgbArg=new int[100*100];
midplet.getImage().getRGB(rgbArg,0,100,0,0,100,100);
byte[] bytes=intTobyte(rgbArg);
os.write(bytes);
//for(int i=0;i<RGBARG.LENGTH;I++){
//os.writeInt(rgbArg[i]);
//System.out.println(rgbArg[i]);
//}
os.flush();
}catch(Exception e){
System.out.println("conn err");
e.printStackTrace();
}finally{
if(os!=null){
try{
os.close();
midplet.setIsSending(false);
midplet.setIsSend(true);
}catch(IOException ioe){};
}
}
midplet.setIsSending(false);
midplet.setIsSend(true);
}
try{
wait();
}catch(Exception e){
System.out.println("wait exception");
e.printStackTrace();
}
}
}
public synchronized void wakeUP(){
notifyAll();
}
private byte[] intTobyte(int[] ints){
byte[] bytes=new byte[ints.length*4];
for(int i=0;i<INTS.LENGTH;I++){
bytes[i*4]=(byte)(0xff&(ints[i]>>>24));
bytes[i*4+1]=(byte)(0xff&(ints[i]>>>16));
bytes[i*4+2]=(byte)(0xff&(ints[i]>>>8));
bytes[i*4+3]=(byte)(0xff&(ints[i]>>>0));
if(i<100){
System.out.println(ints[i]);
}
}
return bytes;
}
客户端的,比上一次多了,一个方法intTobyte()通过这个方法,获得了一个byte类型的数组,直接发送,服务器端,在将这个byte数组还原成一个int数组
=========================================
private void createIamge(DataInputStream io,OutputStream out){
int width = 100;
int height = 100;
int[] rgb=new int[width*height];
try{
int[] bytes=new int[rgb.length*4];
//io.readu(bytes);
//rgb=byteToInt(bytes);
for(int i=0;i<BYTES.LENGTH;I++){
bytes[i]=io.readUnsignedByte();
}
byteToInt(bytes,rgb);
}catch(IOException ioe){ioe.printStackTrace();}
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bi.setRGB(0,0,100,100,rgb,0,100);
bi.flush();
// encode:
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
System.out.println("yeah");
try {
encoder.encode(bi);
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
private void byteToInt(int[] bytes,int[] rgb){
for(int i=0;i<RGB.LENGTH;I++){
rgb[i]=(
((bytes[i*4]&0xff)<<24)|
((bytes[i*4+1]&0xff)<<16)|
((bytes[i*4+2]&0xff)<<8)|
((bytes[i*4+3]&0xff)<<0));
//System.out.print(ints[i]+"\t"+(ints[i]<<8)+"\t");
if(i<100){
System.out.println(rgb[i]);
}
}
}
上面的是服务器端代码,重点在于readUnsignedByte()这方法。不然很难还原int类型。