2011-02-17 7 views
0

에 쓰십시오. 아래 코드를 사용하여 서버에서 이미지 파일을 읽으려고합니다. 그것은 예외로 계속 간다. 받은 바이트를 인쇄 할 때 올바른 바이트 수가 전송된다는 것을 알고 있습니다. Im은 python에서 이미지 파일을 보내려고합니다.Android, 이진 데이터를 읽고 파일

#open the image file and read it into an object 
     imgfile = open (marked_image, 'rb') 
     obj = imgfile.read() 

     #get the no of bytes in the image and convert it to a string 
     bytes = str(len(obj)) 


     #send the number of bytes 
     self.conn.send(bytes + '\n') 




     if self.conn.sendall(obj) == None: 
      imgfile.flush() 
      imgfile.close() 
      print 'Image Sent' 
     else: 
      print 'Error' 

여기는 android 부분입니다. 여기가 문제가되는 곳입니다. 이미지를 받고 파일에 쓰는 가장 좋은 방법에 대한 제안?

//read the number of bytes in the image 
     String noOfBytes = in.readLine(); 


     Toast.makeText(this, noOfBytes, 5).show(); 

     byte bytes [] = new byte [Integer.parseInt(noOfBytes)]; 

     //create a file to store the retrieved image 
     File photo = new File(Environment.getExternalStorageDirectory(), "PostKey.jpg"); 

     DataInputStream dis = new DataInputStream(link.getInputStream()); 
     try{ 


     os =new FileOutputStream(photo); 

     byte buf[]=new byte[1024]; 

     int len; 

     while((len=dis.read(buf))>0) 
     os.write(buf,0,len); 

     Toast.makeText(this, "File recieved", 5).show(); 

     os.close(); 
     dis.close(); 
     }catch(IOException e){ 

      Toast.makeText(this, "An IO Error Occured", 5).show(); 
     } 

편집 : 아직 작동하지 않는 것 같습니다. 그 이후로 내 모든 노력의 결과로 전체 크기가 아닌 파일이 생성되었거나 응용 프로그램이 손상되었습니다. 파일이 서버 쪽을 보내기 전에 손상되지 않았 음을 알고 있습니다. 지금까지 파이썬에서 모든 메소드를 보내면 모든 것을 전송하거나 에러가 발생했을 때 예외를 던지며 지금까지는 예외를 던지지 않았다는 것을 확실히 전달할 수 있습니다. 그래서 클라이언트 쪽이 엉망입니다. 브라이언이 제안한 제안을 사용할 수 없도록 서버에서 파일을 보내야합니다.

+0

데이터를 얻었습니까? 어떤 오류가 발생 했습니까? – dongshengcn

+0

예 바이트 수가 있지만 이미지 데이터는 없습니다. 서버에서 Image가 전송되었고 클라이언트가 io 예외를 포착하고 IO 오류가 발생했다고 표시합니다. – Shpongle

답변

-1

우분투 포럼 회원의 도움으로 문제를 해결했습니다. 문제가되는 바이트를 읽는 것이 었습니다. 이미지에서 일부 바이트를 자르고있었습니다. 해결 방법은 이미지 전체를 보내고 방정식에서 바이트를 모두 함께 제거하는 것입니다.

1

서버에서 비트 맵을 얻는 가장 좋은 방법은 다음을 실행하는 것입니다.

HttpClient client = new DefaultHttpClient(); 

HttpGet get = new HttpGet("http://yoururl"); 

HttpResponse response = client.execute(get); 
InputStream is = response.getEntity().getContent(); 

Bitmap image = BitmapFactory.decodeStream(is); 

이렇게하면 파일에 저장하여 다음과 같은 작업을 수행 할 수 있습니다.

FileOutputStream fos = new FileOutputStream("yourfilename"); 
image.compress(CompressFormat.PNG, 1, fos); 
fos.close(); 

은 또한 두 개의 결합 그냥 디스크에 바로이 도움이

HttpClient client = new DefaultHttpClient(); 

HttpGet get = new HttpGet("http://yoururl"); 

HttpResponse response = client.execute(get); 
InputStream is = response.getEntity().getContent(); 

FileOutputStream fos = new FileOutputStream("yourfilename"); 

byte[] buffer = new byte[256]; 
int read = is.read(buffer); 

while(read != -1){ 
    fos.write(buffer, 0, read); 
    read = is.read(buffer); 
} 

fos.close(); 
is.close(); 

희망을 쓸 수 있습니다;

0

코드를 잘 모르겠습니다. 의 내용을 byte 배열에 쓰려면 dis.readFully(bytes);으로 전화하십시오. 하지만 배열을 가지고 아무 것도하지 않으면 버퍼를 통해 dis의 내용을 FileOutputStream에 쓰려고합니다.

dis.readFully(bytes);을 주석 처리 해보세요. 보조 노트로

, 나는 바이트 수 또는 같은 것들을 위해 건배를 진열보다는 로그에 기록 할 예외가 발생했을 때 :

... 
} catch (IOException e) { 
    Log.e("MyTagName","Exception caught " + e.toString()); 
    e.printStackTrace(); 
} 

당신의 예는 다음 링크에서 볼 수 있었다 SD 카드에 파일을 작성 :

+0

네 맞아, 내 실수는 네트워킹이 처음이야.그것을 주석 처리 한 후 오류가 사라지고 파일이 생성되었지만 토스트가 비어있는 것처럼 빠르게 표시됩니다. 실제 앱에는 없습니다. – Shpongle

+0

@Shpongle 앱을 테스트하는 동안 반드시 오류를 로깅해야합니다 . 이와 같은 문제를보다 신속하게 찾고 수정할 수 있도록 도와줍니다. –

+0

Dave에게 조언을 주셔서 감사합니다. 로그인을 추가합니다. 파일을 쓰고 있지만 데이터 전송이 충분하지 않습니다. 버퍼 크기를 확인해야합니다. – Shpongle