天天看點

選擇照片,設定頭像,上傳頭像

// 選擇照片
private void chooseImage() {
		final CharSequence[] items = { "從相冊選擇", "拍照" };
		AlertDialog dlg = new AlertDialog.Builder(CreateCardActivity.this)
				.setTitle("選擇照片")
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						// 這裡item是根據選擇的方式,在items數組裡面定義了兩種方式,拍照的下标為1是以就調用拍照方法
						if (item == 1) {
							Intent getImageByCamera = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(getImageByCamera, 1);
						} else {
							Intent getImage = new Intent(
									Intent.ACTION_GET_CONTENT);
							getImage.addCategory(Intent.CATEGORY_OPENABLE);
							getImage.setType("image/jpeg");
							startActivityForResult(getImage, 0);
						}
					}
				}).create();
		dlg.show();
	}



// 得到選擇的照片結果
	@Override 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

        ContentResolver resolver = getContentResolver(); 
        byte[] mContent;
		Bitmap myBitmap = null;
		/**
         * 因為兩種方式都用到了startActivityForResult方法,這個方法執行完後都會執行onActivityResult方法,
         * 是以為了差別到底選擇了那個方式擷取圖檔要進行判斷,這裡的requestCode跟startActivityForResult裡面第二個參數對應
         */
        if (requestCode == 0) { 
            try { 
                //獲得圖檔的uri 
                Uri originalUri = data.getData(); 
                //将圖檔内容解析成位元組數組  
                mContent=readStream(resolver.openInputStream(Uri.parse(originalUri.toString())));
                //将位元組數組轉換為ImageView可調用的Bitmap對象 
                myBitmap = getPicFromBytes(mContent, null); 
                把得到的圖檔綁定在控件上顯示
                img_head.setImageBitmap(myBitmap);
            } catch (Exception e) { 
                System.out.println(e.getMessage()); 
            } 

        }else if(requestCode ==1){
        	try {
	        	super.onActivityResult(requestCode, resultCode, data);
		    	Bundle extras = data.getExtras();
		    	myBitmap = (Bitmap) extras.get("data");
		    	ByteArrayOutputStream baos = new ByteArrayOutputStream();     
		    	myBitmap.compress(Bitmap.CompressFormat.JPEG , 100, baos);     
				mContent=baos.toByteArray();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//把得到的圖檔綁定在控件上顯示
			img_head.setImageBitmap(myBitmap);
        }

    } 

	public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) { 
        if (bytes != null) 
            if (opts != null) 
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,opts); 
            else 
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
        return null; 
    }

	public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
                 outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }



// 上傳照片
	private void uploadHeadImage() throws IOException{
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(Constant.uploadHeadUrl+"id=1");

        Drawable drawable = img_head.getDrawable();
        Bitmap bmp = ((BitmapDrawable)drawable).getBitmap(); 
        FileOutputStream fop = new FileOutputStream("/mnt/sdcard/temp/kkpy_head.jpg");
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fop);
		//壓縮bitmap寫進outputStream 參數:輸出格式  輸出品質  目标OutputStream
		//格式可以為jpg,png,jpg不能存儲透明
		fop.close();
		File file = new File("/mnt/sdcard/temp/kkpy_head.jpg");

        FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");

        httppost.setEntity(reqEntity);
        //httppost.getParams().setParameter("id", "1");
        reqEntity.setContentType("binary/octet-stream");
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (resEntity != null) {
          System.out.println(EntityUtils.toString(resEntity));
        }
        if (resEntity != null) {
          resEntity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();
	}