我现在已经得到一个bitmap对象,用socket通信,应该怎么把bitmap对象通过socket传到服务器呢?哪位好心人能最好能附上代码,或怎么把bitmap成inputstream?
谢谢

解决方案 »

  1.   

    你这个不就像上传文件么,你先获取图片的地址,然后通过下面步骤:
    1、设置传送的method=POST
    2、设置DataOutputStrem
    3、获取文件的FileInputStream
    4、设置每次写入1024个字节
    5、从文件读取数据至缓冲区
    6、获取Response的内容
      

  2.   

    楼主应该是要的c/s结构吧 不是用web server。你是要传bitmap对象还是文件。
      

  3.   

    private byte[] getBitmapData(Bitmap photo) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    return baos.toByteArray();
    }
    然后把这个byte[]数组发送过去,接收方使用BitmapFactory.decodeByteArray()函数生成Bitmap就好了
      

  4.   

    需要将bitmap图片文件转换成base64编码,然后通过socket发送出去。
    有人会问 为什么要转换成base64,而不用String 直接发送呢,原因是将图片直接转换成String会有很多特殊字符,倒制在传输过程中特殊字符所带来的问题。而转换成base64编码后都是一些数字与字母的组合,不会有特殊字符。
      

  5.   

    对,我用的是c/s结构,我想用objectoutput传过去,有一个bitmap对象,最好能直接传,手机里也有图片文件,但获取文件地址是不是比较麻烦?
      

  6.   


    也一样要 用文件直接给个路径用流打开,发送也是按byte[]发送的,
    先发送文件名 再文件大小 再发送数据。
    服务端链接后设读超时 先收文件名 再收文件大小 在一边收一边写文件 超时或收完就结束了
      

  7.   

    请问能不能给个代码,我是新手,有点不是很明白怎么实现?还有就是我一个是从gallery里面获取的数据,用data.getData()获取了uri,但好象不能直接用这个uri读那个文件,是怎么回事?
      

  8.   

    uri需要转换一下才能得到真实路径的
    代码要等等。。
      

  9.   


    我现在就是不太会 很纠结啊 我把我代码发上来 你看哈,或是你能加我q吗 240702530package phx.Activity;public class AddCommentActivity extends Activity{
    private String username = null;
    private String sightname = null;
    private EditText editText = null;
    private Button addButton = null;
    private String nickname = null;
    private Button addPicture = null;
    private ImageView preView = null;
    private Uri originalUri= null;
    private Bitmap b = null;
    private Bitmap bs = null;
    private static final int CAMERA_WITH_DATA = 3023;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.addcommentactivity);
            Intent intent = getIntent();
            username = intent.getStringExtra("username");
            sightname = intent.getStringExtra("sightname");
            nickname = intent.getStringExtra("nickname");
            System.out.println(username+"  "+sightname);
            editText = (EditText)findViewById(R.id.AddCommentEditText);
            addPicture = (Button)findViewById(R.id.AddPicture);
            addPicture.setOnClickListener(new addPictureButtonListener());
            preView = (ImageView)findViewById(R.id.Commentpicture);
            addButton = (Button)findViewById(R.id.AddButton);
            addButton.setOnClickListener(new addButtonListener());
            
    }
    class addPictureButtonListener implements Button.OnClickListener{ @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
    addPictureDialog();

    }

    }
    private void addPictureDialog(){
    new AlertDialog.Builder(this).setTitle("Get From").setItems(
         new String[] { "Camera", "Gallery" },new DialogInterface.OnClickListener(){ @Override
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub
    if(arg1==0){
    handler.post(GetCamera);
    }
    else{
    handler.post(getGallary);
    }
    System.out.println(arg1);
    }
          
         }
    ).setNegativeButton("Cancel",null).show();

    }
    Runnable getGallary = new Runnable(){    
         public void run(){
        
    Intent mIntent= new Intent(Intent.ACTION_GET_CONTENT); mIntent.addCategory(Intent.CATEGORY_OPENABLE);

    mIntent.setType("image/*");
    startActivityForResult(mIntent,PHOTO_PICKED_WITH_DATA);
    }};Runnable GetCamera = new Runnable(){
    public void run(){
    String status=Environment.getExternalStorageState();    if(status.equals(Environment.MEDIA_MOUNTED)){

                                  
    Intent mIntent = new Intent("android.media.action.IMAGE_CAPTURE"); 
    // 图片存储路径,可自定义
    File tmpFile = new File(Environment.getExternalStorageDirectory(),"camera.jpg"); // 获取这个图片的URI originalUri = Uri.fromFile(tmpFile);//这是个实例变量,方便下面获取图片的时候用 mIntent.putExtra(MediaStore.EXTRA_OUTPUT, originalUri);

    startActivityForResult(mIntent, CAMERA_WITH_DATA);

    }
    else {
    Toast.makeText(AddCommentActivity.this, "nosdcard", Toast.LENGTH_SHORT).show();
    }
    }};
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // FileOutputStream output = null;
    // String filePath =Environment.getExternalStorageDirectory().toString()+"/camera.jpg";
        try {
         if (resultCode != RESULT_OK) {     return;     }
         if(requestCode==CAMERA_WITH_DATA){
         String pathString = Environment.getExternalStorageDirectory().toString() + "/camera.jpg";
            b= BitmapFactory.decodeFile(pathString);
            bs = imageScale(b,45,45);
            preView.setImageBitmap(bs);
            preView.setVisibility(View.VISIBLE);     }
         if(requestCode==PHOTO_PICKED_WITH_DATA){
         System.out.println("1");
         ContentResolver resolver = getContentResolver();
         originalUri = data.getData(); 
         b = MediaStore.Images.Media.getBitmap(resolver, originalUri);     bs = imageScale(b,45,45);
                preView.setImageBitmap(bs);
                preView.setVisibility(View.VISIBLE);
                System.out.println("2");
         }
            if (resultCode == 1) {
                return;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
           
            System.gc();
        }};

    class addButtonListener implements Button.OnClickListener{ @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
    handler.post(AddCommentThread);
    }
    }
    Handler handler = new Handler(){ @Override
    public void handleMessage(Message msg) {
    // TODO Auto-generated method stub

    }
        };
        
        Runnable AddCommentThread = new Runnable(){
     public void run(){
     Socket socket = null;
     ArrayList<String> commentNickname = new ArrayList<String>();
     ArrayList<String> sightComment = new ArrayList<String>();
     ArrayList<Bitmap> commentImage = new ArrayList<Bitmap>();

     
     int i = 0;
     String str [] = null; 
     str = new String [4];
     str[0] = username;
     str[1] = sightname;
     str[2] = nickname;
     str[3] = editText.getText().toString();
       
     try {
     
     if(str[3].equals("")&&b==null){
     
     Toast.makeText(AddCommentActivity.this, "Sorry, Please write the comment or add a picture.", Toast.LENGTH_SHORT).show();
     }
     else {
     
     if(str[3]==null){
     str[3]="nocomment";
     }
    socket = new Socket("192.168.1.64",4449);
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    String picture_flag = null;
    // socket = new Socket("143.210.195.163",4449);
    //向服务器发送消息
    while (i<=3){
    oos.writeObject(str[i]);
    System.out.println(str[i]);
    i++;
    }
    if(b==null){
    picture_flag = "nopicture";
    oos.writeObject(picture_flag);
    }
    else {
    picture_flag = "picture";
    oos.writeObject(picture_flag);
    byte[] buffer = Bitmap2Bytes(b);
    oos.write(buffer);
    }
    oos.writeObject(null);
    //接收来自服务器的消息
    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Object got=ois.readObject();
    //接收来自服务器的消息
    while(got!=null){
        
                    System.out.print("Server发来的是");
                    if (got instanceof String){
                    
                     if(got.toString().equals("nopicture")){
                     commentImage.add(null);
                     System.out.println("1");
                     }
                     else{
                        System.out.println("字符串:" + got);
                        String [] split = null;
        
         split = got.toString().split("=!=!");
         commentNickname.add(split[0]);
         sightComment.add(split[1]);
                     }}
                    if (got instanceof byte[]){
                        
                        System.out.println("图片,存往文件");
              
                        if(((byte[])got).length!=0){  
                           Bitmap bitmap3= BitmapFactory.decodeByteArray((byte[])got, 0, ((byte[])got).length);  
                            commentImage.add(bitmap3
                             );
                        }  
                   
                    }
                 got = ois.readObject();  
                }

    Intent intent = new Intent();
    Bundle bundle = new Bundle();
    bundle.putStringArrayList("commentNickname", commentNickname);
    bundle.putStringArrayList("sightComment", sightComment);
    bundle.putParcelableArrayList("picture", commentImage);
    intent.putExtras(bundle);
    intent.putExtra("username", username);
    intent.putExtra("sightname", sightname);
    intent.putExtra("nickname", nickname);
    intent.setClass(AddCommentActivity.this, SightCommentActivity.class);
    AddCommentActivity.this.startActivity(intent); System.out.println("finish");

    //关闭流 //关闭Socket
    socket.close();  
     }
     }
    catch (Exception e) 
    {
    // TODO: handle exception
    e.printStackTrace();
    }
     
     }
     }  ;
     public static Bitmap imageScale(Bitmap bitmap, int dst_w, int dst_h){
    //      public static Bitmap imageScale(Bitmap bitmap){
           int  src_w = bitmap.getWidth();
           int  src_h = bitmap.getHeight();
           float scale_w = ((float)dst_w)/src_w;
           float  scale_h = ((float)dst_h)/src_h;
    //       float scale_w = (float) 0.3;
    //       float scale_h = (float) 0.3;
           Matrix  matrix = new Matrix();
           matrix.postScale(scale_w, scale_h);
           Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, src_w, src_h, matrix, true);
           
           return dstbmp;
          };
          private byte[] Bitmap2Bytes(Bitmap bm){  
          ByteArrayOutputStream baos = new ByteArrayOutputStream();   
          bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
          return baos.toByteArray();  
          }  ;
     
    }
      

  10.   

    写了个发送函数 直接bitmap对象的话可以先用Bitmap.compress获取OutputStream在发送,直接用路径发
    用uri也可以用File file = new File(uri)读取
    public  void SendFileClient(String ipaddr,int port,String fname) 
    {
    Socket socket = null;
    try
    {
            File file = new File(fname);
            if(file.exists()==false) return;
            FileInputStream fin = new FileInputStream(file);  
            
               InetAddress serverAddr = InetAddress.getByName(ipaddr); 
               socket = new Socket(serverAddr, port ); 
               OutputStream out =   socket.getOutputStream();             /*发送文件名*/
               out.write( file.getName().getBytes());
               out.write(13);        //PC端可用readln接收
                /*发送文件大小*/
               int fsize=fin.available();
               out.write(fsize&0xFF);
               fsize>>=8;
               out.write(fsize&0xFF);
               fsize>>=8;
               out.write(fsize&0xFF);
               fsize>>=8;
               out.write(fsize&0xFF);
               out.flush();
               
                /*发送文件*/ 
               byte[] buffer=new byte[1000];
               int ln=0;
               while((ln=fin.read(buffer))>0)
                {
                out.write(buffer,0,ln);
                }
        socket.close();
            } 
    catch (Exception e) 
            { 
     e.printStackTrace();
     if( (socket!=null) && socket.isConnected())
     {
    try {
     
    socket.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
     }
     socket=null;
            }
    }    
      

  11.   

    非常感谢,但你看我是这样写的
    发送端代码(这里尝试了两种方式,注释里面是直接压入outputstream,和转成byte数组方式)ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    Bitmap b;
    byte []buffer = null;
          buffer = Bitmap2Bytes(b);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
             bos.write(buffer);
                            
    //    b.compress(Bitmap.CompressFormat.JPEG, 50, bos);
                        
        oos.write(bos.toByteArray());接收端
    ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
       Object got=ois.readObject();
    while(got!=null){if (got instanceof byte[]){          
     if(((byte[])got).length!=0){  
     String fileName = "D:\\copy.jpg";
     System.out.println("图片,存往文件:" + fileName )                        
     FileOutputStream fos = new FileOutputStream( fileName );
     fos.write( (byte[])got );
     fos.flush();
            fos.close();                   
     }  
        got = ois.readObject();  
          }用这种方式传输可以吗? 主要是bitmap那一段,但是会出现java.io.OptionalDataException异常,为什么,应该如何解决?
      

  12.   


    Bitmap b; 都没初始化。
      

  13.   


    初始画了,里面是有数据的,我从gallary里面提取的照片,然后传的
    ContentResolver resolver = getContentResolver();
    originalUri = data.getData(); 
    b = MediaStore.Images.Media.getBitmap(resolver, originalUri);
      

  14.   

    LZ可以参考下这篇笔记
    http://blog.csdn.net/fff32165/article/details/6731338