Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android上傳圖片及下載圖片並顯示

android上傳圖片及下載圖片並顯示

編輯:關於Android編程

1、項目需要打開攝像頭,拍照,然後上傳照片。

首先定義一個“拍照”按鈕,用來跳轉到另一個Activity:


[java] protected void takePhoto() { 
        // TODO Auto-generated method stub  
         
        String sdStatus = Environment.getExternalStorageState(); 
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) 
        { // 檢測sd是否可用  
            Log.i("exception", 
                    "SD card is not avaiable/writeable right now."); 
            Toast.makeText(getApplicationContext(), "sd卡無法使用", 
                     Toast.LENGTH_SHORT).show(); 
            return; 
        } 
        
          File file = new File( 
                Environment.getExternalStorageDirectory().getAbsolutePath() 
                +File.separator+"myAQ"+File.separator); 
        if(!file.exists()) 
            file.mkdirs();// 創建文件夾             
        
        String time = new SimpleDateFormat( 
                "yyyyMMddHHmmss").format(new Date()); 
        fileName = time+".jpg"; 
        Intent intent = new Intent(PublishNewsActivity.this,TakePhotoActivity.class);    
        intent.putExtra("fileName", fileName); 
        startActivityForResult(intent, 10);  
         
    } 

protected void takePhoto() {
  // TODO Auto-generated method stub
  
  String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED))
        { // 檢測sd是否可用
            Log.i("exception",
                    "SD card is not avaiable/writeable right now.");
            Toast.makeText(getApplicationContext(), "sd卡無法使用",
         Toast.LENGTH_SHORT).show();
            return;
        }
      
          File file = new File(
          Environment.getExternalStorageDirectory().getAbsolutePath()
    +File.separator+"myAQ"+File.separator);
        if(!file.exists())
         file.mkdirs();// 創建文件夾          
      
  String time = new SimpleDateFormat(
    "yyyyMMddHHmmss").format(new Date());
  fileName = time+".jpg";
  Intent intent = new Intent(PublishNewsActivity.this,TakePhotoActivity.class); 
  intent.putExtra("fileName", fileName);
  startActivityForResult(intent, 10); 
       
 }在拍照的Activity會打開攝像頭,點擊拍照按鈕可以拍照並返回上一個Activity。


[java]  import java.io.File; 
import java.io.FileOutputStream; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.ImageFormat; 
import android.graphics.Matrix; 
import android.graphics.PixelFormat; 
import android.graphics.Bitmap.CompressFormat; 
import android.hardware.Camera; 
import android.hardware.Camera.PictureCallback; 
import android.os.Bundle; 
import android.os.Environment; 
import android.app.Activity; 
import android.content.Intent; 
import android.util.DisplayMetrics; 
import android.util.Log; 
import android.view.Menu; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import android.view.View; 
import android.view.Window; 
import android.view.WindowManager; 
import android.view.SurfaceHolder.Callback; 
import android.widget.Button; 
import android.widget.FrameLayout; 
import android.widget.LinearLayout; 
import android.widget.RelativeLayout; 
import android.widget.Toast; 
 
public class TakePhotoActivity extends Activity { 
 
    private SurfaceView mSurfaceView; 
    private SurfaceHolder mHolder; 
    protected Camera camera; 
    private Button start; 
    private String photoName; 
    private int window_width; 
    private int window_height; 
     
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        Window window = getWindow(); 
        requestWindowFeature(Window.FEATURE_NO_TITLE);//沒有標題  
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//設置全屏  
        getWindow().setFormat(PixelFormat.TRANSLUCENT);//設置半透明  
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//設置高亮        
        setContentView(R.layout.activity_take_photo); 
         
        DisplayMetrics dm = new DisplayMetrics(); 
        this.getWindowManager().getDefaultDisplay().getMetrics(dm); 
        window_width = dm.widthPixels;//屏幕寬度  
        window_height  = dm.heightPixels;//屏幕高度   
        //Log.i("test", window_width+":"+window_height);  
         
        start=(Button)findViewById(R.id.take_picture_Button); 
         
        mSurfaceView=(SurfaceView)findViewById(R.id.takePicture_surfaceview);//初始預覽窗口  
        photoName = (String)(this.getIntent().getExtras().getString("fileName")); 
        LinearLayout.LayoutParams param  =    
                new LinearLayout.LayoutParams( 
                        window_height*4/3,window_height); 
        param.leftMargin=(window_width-param.width)/2; 
        Log.i("test", param.width+":"+param.height+":"+param.leftMargin); 
        //findViewById(R.id.takePicture_activity).setLayoutParams(param);  
        //mSurfaceView.getHolder().setFixedSize(window_height*4/3,window_height);  
        mSurfaceView.setLayoutParams(param); 
         
 
        start.setOnClickListener( 
                new View.OnClickListener() { 
                    @Override 
                    public void onClick(View view) { 
                        startShot(); 
                                         
                    } 
                });  
         
        // 綁定初始預覽視圖  
        mHolder = mSurfaceView.getHolder(); 
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
        mHolder.addCallback(new Callback() { 
 
            @Override 
            public void surfaceDestroyed(SurfaceHolder holder) { 
                 
                camera.stopPreview(); 
                camera.release(); 
                camera = null; // 記得釋放                
                mSurfaceView = null; 
                 
            } 
 
            @Override 
            public void surfaceCreated(SurfaceHolder holder) { 
                try { 
                    camera = Camera.open(); 
                    //Log.i("why","1");  
                    Camera.Parameters parameters = camera.getParameters(); 
                    parameters.setPreviewFrameRate(24); // 每秒24幀  
                    parameters.setPictureSize(640, 480); 
                    parameters.setPictureFormat(ImageFormat.JPEG);// 設置照片的輸出格式  
                    parameters.set("jpeg-quality", 100);// 照片質量  
                    parameters.setPreviewSize(640, 480); 
                    //parameters.setPreviewFormat(ImageFormat.NV21);  
                    /* 獲取支持的尺寸
                    List<Camera.Size> pszize = parameters.getSupportedPictureSizes(); 
                    
                    if (null != pszize && 0 < pszize.size()) { 
                        int height[] = new int[pszize.size()]; 
                        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 
                        for (int i = 0; i < pszize.size(); i++) { 
                            Camera.Size size = (Camera.Size) pszize.get(i); 
                            int sizeheight = size.height; 
                            int sizewidth = size.width; 
                            height[i] = sizeheight; 
                            map.put(sizeheight, sizewidth); 
                            Log.i("height","h"+sizeheight+"w"+sizewidth);
                        } 
                        Arrays.sort(height); 
                    }
                    */ 
                    camera.setParameters(parameters); 
                    camera.setPreviewDisplay(holder); 
                    //Log.i("why","2");  
                    camera.startPreview();                   
                    //Log.i("why","3");  
                } catch (Exception e) { 
                    camera.release(); 
                    Log.i("why",e.getMessage()); 
                } 
                 
            } 
 
            @Override 
            public void surfaceChanged(SurfaceHolder holder, int format, 
                    int width, int height) { 
                 
            } 
        }); 
         
    } 
    protected void startShot() { 
         
        // TODO Auto-generated method stub  
         
        if (camera != null) { 
             
            camera.autoFocus(null); 
            camera.takePicture(null, null, callback );           
        } 
         
         
         
    }    
                   
 
 
     
    PictureCallback callback=new PictureCallback() { 
        @Override 
        public void onPictureTaken(byte[] data, Camera camera) { 
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 
                    0, data.length); 
            Matrix matrix = new Matrix(); 
            // 設置縮放  
            matrix.postScale(1f, 1f); 
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, 
                    bitmap.getWidth(), bitmap.getHeight(), 
                    matrix, true); 
 
            String shot_path = Environment.getExternalStorageDirectory().getAbsolutePath() 
                    +File.separator+"myAQ"+File.separator ; 
            String shot_fileName = photoName; 
            File shot_out = new File(shot_path); 
            if (!shot_out.exists()) { 
                shot_out.mkdirs(); 
            } 
            shot_out = new File(shot_path, shot_fileName); 
            try { 
                FileOutputStream outStream = new FileOutputStream(shot_out); 
                bitmap.compress(CompressFormat.JPEG,90, 
                        outStream); 
                outStream.close(); 
//              Toast.makeText(getApplicationContext(),  
//                      "拍攝完成~",  
//                       Toast.LENGTH_SHORT).show();  
//              Intent mIntent = new Intent(Upload_takePicture.this,UploadActivity.class);  
//              mIntent.putExtra("photoName", photoName);  
//              mIntent.putExtra("userId", user);  
                 
//              mIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  
//              startActivity(mIntent);  
                Intent i=new Intent();    
                //請求代碼可以自己設置,這裡設置成20    
                setResult(RESULT_OK, i);   
                TakePhotoActivity.this.finish();         
                //camera.startPreview();  
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
                         
        } 
    }; 
 

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.SurfaceHolder.Callback;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class TakePhotoActivity extends Activity {

 private SurfaceView mSurfaceView;
 private SurfaceHolder mHolder;
 protected Camera camera;
 private Button start;
 private String photoName;
 private int window_width;
 private int window_height;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Window window = getWindow();
  requestWindowFeature(Window.FEATURE_NO_TITLE);//沒有標題
  window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
          WindowManager.LayoutParams.FLAG_FULLSCREEN);//設置全屏
  getWindow().setFormat(PixelFormat.TRANSLUCENT);//設置半透明
  window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//設置高亮  
  setContentView(R.layout.activity_take_photo);
  
  DisplayMetrics dm = new DisplayMetrics();
  this.getWindowManager().getDefaultDisplay().getMetrics(dm);
  window_width = dm.widthPixels;//屏幕寬度
  window_height  = dm.heightPixels;//屏幕高度 
  //Log.i("test", window_width+":"+window_height);
  
  start=(Button)findViewById(R.id.take_picture_Button);
  
  mSurfaceView=(SurfaceView)findViewById(R.id.takePicture_surfaceview);//初始預覽窗口
  photoName = (String)(this.getIntent().getExtras().getString("fileName"));
  LinearLayout.LayoutParams param  =  
             new LinearLayout.LayoutParams(
               window_height*4/3,window_height);
  param.leftMargin=(window_width-param.width)/2;
  Log.i("test", param.width+":"+param.height+":"+param.leftMargin);
  //findViewById(R.id.takePicture_activity).setLayoutParams(param);
  //mSurfaceView.getHolder().setFixedSize(window_height*4/3,window_height);
  mSurfaceView.setLayoutParams(param);
  

  start.setOnClickListener(
    new View.OnClickListener() {
     @Override
     public void onClick(View view) {
      startShot();
          
     }
    });
  
  // 綁定初始預覽視圖
     mHolder = mSurfaceView.getHolder();
     mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
     mHolder.addCallback(new Callback() {

         @Override
         public void surfaceDestroyed(SurfaceHolder holder) {
          
             camera.stopPreview();
             camera.release();
             camera = null; // 記得釋放            
             mSurfaceView = null;
            
         }

         @Override
         public void surfaceCreated(SurfaceHolder holder) {
             try {
                 camera = Camera.open();
                 //Log.i("why","1");
                 Camera.Parameters parameters = camera.getParameters();
                 parameters.setPreviewFrameRate(24); // 每秒24幀
                 parameters.setPictureSize(640, 480);
                 parameters.setPictureFormat(ImageFormat.JPEG);// 設置照片的輸出格式
                 parameters.set("jpeg-quality", 100);// 照片質量
                 parameters.setPreviewSize(640, 480);
                 //parameters.setPreviewFormat(ImageFormat.NV21);
                 /* 獲取支持的尺寸
                 List<Camera.Size> pszize = parameters.getSupportedPictureSizes();
                
                 if (null != pszize && 0 < pszize.size()) {
                     int height[] = new int[pszize.size()];
                     HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
                     for (int i = 0; i < pszize.size(); i++) {
                         Camera.Size size = (Camera.Size) pszize.get(i);
                         int sizeheight = size.height;
                         int sizewidth = size.width;
                         height[i] = sizeheight;
                         map.put(sizeheight, sizewidth);
                         Log.i("height","h"+sizeheight+"w"+sizewidth);
                     }
                     Arrays.sort(height);
                 }
                 */
                 camera.setParameters(parameters);
                 camera.setPreviewDisplay(holder);
                 //Log.i("why","2");
                 camera.startPreview();                
                 //Log.i("why","3");
             } catch (Exception e) {
              camera.release();
              Log.i("why",e.getMessage());
             }
            
         }

         @Override
         public void surfaceChanged(SurfaceHolder holder, int format,
                 int width, int height) {
            
         }
     });
  
 }
 protected void startShot() {
  
  // TODO Auto-generated method stub
  
  if (camera != null) {
   
   camera.autoFocus(null);
   camera.takePicture(null, null, callback );    
  }
  
  
  
 }  
           


 
 PictureCallback callback=new PictureCallback() {
  @Override
  public void onPictureTaken(byte[] data, Camera camera) {
   Bitmap bitmap = BitmapFactory.decodeByteArray(data,
     0, data.length);
   Matrix matrix = new Matrix();
   // 設置縮放
   matrix.postScale(1f, 1f);
   bitmap = Bitmap.createBitmap(bitmap, 0, 0,
     bitmap.getWidth(), bitmap.getHeight(),
     matrix, true);

   String shot_path = Environment.getExternalStorageDirectory().getAbsolutePath()
     +File.separator+"myAQ"+File.separator ;
   String shot_fileName = photoName;
   File shot_out = new File(shot_path);
   if (!shot_out.exists()) {
    shot_out.mkdirs();
   }
   shot_out = new File(shot_path, shot_fileName);
   try {
    FileOutputStream outStream = new FileOutputStream(shot_out);
    bitmap.compress(CompressFormat.JPEG,90,
      outStream);
    outStream.close();
//    Toast.makeText(getApplicationContext(),
//      "拍攝完成~",
//          Toast.LENGTH_SHORT).show();
//    Intent mIntent = new Intent(Upload_takePicture.this,UploadActivity.class);
//    mIntent.putExtra("photoName", photoName);
//    mIntent.putExtra("userId", user);
    
//    mIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//    startActivity(mIntent);
    Intent i=new Intent();  
             //請求代碼可以自己設置,這裡設置成20 
             setResult(RESULT_OK, i); 
    TakePhotoActivity.this.finish();  
    //camera.startPreview();
   } catch (Exception e) {
    e.printStackTrace();
   }
      
  }
 };

}
拍完照片後,顯示在一個imageView上。


[java] @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        super.onActivityResult(requestCode, resultCode, data); 
 
        if (resultCode == RESULT_OK) 
        { 
             ImageView imageView = (ImageView) findViewById(R.id.publish_imageview);   
               picPath=Environment.getExternalStorageDirectory().getAbsolutePath() 
                    +File.separator+"myAQ"+File.separator+fileName;  
               imageView.setImageBitmap(BitmapFactory.decodeFile(picPath));  
        } 
         
    } 

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK)
        {
          ImageView imageView = (ImageView) findViewById(R.id.publish_imageview); 
            picPath=Environment.getExternalStorageDirectory().getAbsolutePath()
           +File.separator+"myAQ"+File.separator+fileName;
            imageView.setImageBitmap(BitmapFactory.decodeFile(picPath));
        }
       
    }發布按鈕是如下定義,需要注意的是:先將所有內容放到一個JSONObject(包含圖片的編碼),然後在將這個JSONObject封裝到nameValuePair中,這樣的好處是JSON更輕量級。(沒有將照片轉碼的String直接放到nameValuePair中,這樣試了一次,出問題了,沒有找到問題)

 

[java]  protected void publish_news() 
    { 
        // TODO Auto-generated method stub  
        ArrayList<String> paraName = new ArrayList<String>(); 
        ArrayList<String> paraValue = new ArrayList<String>(); 
        EditText publish_newstitle=(EditText)findViewById(R.id.publish_newstitle); 
        if(publish_newstitle.getText()==null||publish_newstitle.getText().toString().trim().equals("")) 
        { 
             
            publish_newstitle.setError("請填寫新聞標題"); 
            publish_newstitle.requestFocus(); 
            return; 
        } 
        EditText publish_newscontent=(EditText)findViewById(R.id.publish_newscontent); 
        if(publish_newscontent.getText()==null||publish_newscontent.getText().toString().trim().equals("")) 
        { 
            publish_newscontent.setError("請填寫新聞內容"); 
            publish_newscontent.requestFocus(); 
            return; 
        } 
      int x=(int)(latitude*1000000); 
      int y=(int)(longitude*1000000); 
      userID=getSharedPreferences("user_info",MODE_WORLD_READABLE); 
        paraName.add("userId"); 
        paraValue.add(userID.getString("userID", null)); 
        paraName.add("news_type"); 
        paraValue.add(news_type); 
        paraName.add("news_title"); 
        paraValue.add(publish_newstitle.getText().toString()); 
        paraName.add("news_content"); 
        paraValue.add(publish_newscontent.getText().toString()); 
        paraName.add("x"); 
        paraValue.add(x+""); 
        paraName.add("y"); 
        paraValue.add(y+""); 
 
        try 
        { 
 
            File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() 
                    +File.separator+"myAQ"+File.separator+fileName); 
             
            FileInputStream pfis=new FileInputStream(photoFile);             
            ByteArrayOutputStream pbaos=new ByteArrayOutputStream(); 
            byte[] buffer=new byte[1024];            
            while(pfis.read(buffer)>0) 
            { 
                pbaos.write(buffer); 
            } 
             
            String photoData= 
                    new String(Base64.encode(pbaos.toByteArray(),Base64.DEFAULT));                   
            pfis.close(); 
            paraName.add("image"); 
            paraValue.add(photoData);    
             JSONObject jsonObj = new JSONObject(); 
             for(int i = 0; i < paraName.size(); i++) 
             { 
                jsonObj.put(paraName.get(i), paraValue.get(i)); 
             }         
             String jsonString = jsonObj.toString(); 
             Log.i("test", "upload:"+jsonString); 
             //指定Post參數  
           //  String encodeString = URLEncoder.encode(jsonString, "utf-8");  
             List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
             nameValuePairs.add(new BasicNameValuePair("data", jsonString)); 
           String result = HttpClientTest.doPost(nameValuePairs, Constant.publish_newsURL);        
                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); 
                PublishNewsActivity.this.finish(); 
        } 
        catch(Exception e) 
        { 
            Log.i("exception","submit:" + e.getMessage()); 
            Toast.makeText(getApplicationContext(), "提交失敗",Toast.LENGTH_SHORT).show(); 
        } 
         
    } 

protected void publish_news()
 {
  // TODO Auto-generated method stub
  ArrayList<String> paraName = new ArrayList<String>();
     ArrayList<String> paraValue = new ArrayList<String>();
     EditText publish_newstitle=(EditText)findViewById(R.id.publish_newstitle);
     if(publish_newstitle.getText()==null||publish_newstitle.getText().toString().trim().equals(""))
     {
      
      publish_newstitle.setError("請填寫新聞標題");
      publish_newstitle.requestFocus();
      return;
     }
     EditText publish_newscontent=(EditText)findViewById(R.id.publish_newscontent);
     if(publish_newscontent.getText()==null||publish_newscontent.getText().toString().trim().equals(""))
     {
      publish_newscontent.setError("請填寫新聞內容");
      publish_newscontent.requestFocus();
      return;
     }
   int x=(int)(latitude*1000000);
   int y=(int)(longitude*1000000);
   userID=getSharedPreferences("user_info",MODE_WORLD_READABLE);
     paraName.add("userId");
     paraValue.add(userID.getString("userID", null));
     paraName.add("news_type");
     paraValue.add(news_type);
     paraName.add("news_title");
     paraValue.add(publish_newstitle.getText().toString());
     paraName.add("news_content");
     paraValue.add(publish_newscontent.getText().toString());
     paraName.add("x");
     paraValue.add(x+"");
     paraName.add("y");
     paraValue.add(y+"");

     try
     {

      File photoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
     +File.separator+"myAQ"+File.separator+fileName);
      
      FileInputStream pfis=new FileInputStream(photoFile);   
      ByteArrayOutputStream pbaos=new ByteArrayOutputStream();
      byte[] buffer=new byte[1024];   
      while(pfis.read(buffer)>0)
      {
       pbaos.write(buffer);
      }
      
      String photoData=
        new String(Base64.encode(pbaos.toByteArray(),Base64.DEFAULT));        
      pfis.close();
      paraName.add("image");
      paraValue.add(photoData); 
       JSONObject jsonObj = new JSONObject();
          for(int i = 0; i < paraName.size(); i++)
          {
           jsonObj.put(paraName.get(i), paraValue.get(i));
          }       
          String jsonString = jsonObj.toString();
          Log.i("test", "upload:"+jsonString);
          //指定Post參數
        //  String encodeString = URLEncoder.encode(jsonString, "utf-8");
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
          nameValuePairs.add(new BasicNameValuePair("data", jsonString));
     String result = HttpClientTest.doPost(nameValuePairs, Constant.publish_newsURL);      
          Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
          PublishNewsActivity.this.finish();
     }
     catch(Exception e)
     {
      Log.i("exception","submit:" + e.getMessage());
      Toast.makeText(getApplicationContext(), "提交失敗",Toast.LENGTH_SHORT).show();
     }
    
 }

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved