AndroidGUI29:獲取ImageView中的圖像需要註意的問題 – Android移動開發技術文章_手機開發 Android移動開發教學課程

我們知道在Android中ImageView是一個用於顯示圖像的控件,比如在很多聯系人方面的應用中,需要為聯系人拍攝頭像,並將得到的頭像放在一個ImageView對象中顯示。通常,在沒有為聯系人拍攝頭像之前,ImageView對象中顯示的是一個缺省的圖片。因此,在保存聯系人頭像數據時,需要比較拍攝前和拍攝後兩個圖像是否一致,因為拍攝後是可能取消拍攝結果的,因此有可能造成拍攝動作發生前後ImageView中顯示的是同一個圖像。隻有當不一樣時,才將ImageView對象中的圖像保存到數據庫中,否則不用保存,這樣一方面可以提高性能,另一方面可以節省空間。
 

根據上面的思路,我們可以在開始拍攝前獲取ImageView對象中的圖像,在保存數據的時候,再次從該ImageView對象中獲取圖像,然後比較先後所得到的像個圖像是否一致,並進行進一步的處理。

 

從ImageView對象中獲取圖像的方法是什麼呢?

從ImageView對象中獲取圖像的方法,就是ImageView類中的getDrawingCache()方法,比如下面的代碼就是從一個ImageView對象iv_photo中獲取圖像:

Bitmap obmp = Bitmap.createBitmap(iv_photo.getDrawingCache());

 

但是需要說明的是:

1.     在調用getDrawingCache()方法從ImageView對象獲取圖像之前,一定要調用setDrawingCacheEnabled(true)方法:

            iv_photo.setDrawingCacheEnabled(true);

        否則,無法從ImageView對象iv_photo中獲取圖像;

2.     在調用getDrawingCache()方法從ImageView對象獲取圖像之後,一定要調用setDrawingCacheEnabled(false)方法:

            iv_photo.setDrawingCacheEnabled(false);

        以清空畫圖緩沖區,否則,下一次從ImageView對象iv_photo中獲取的圖像,還是原來的圖像。

 

下面,我們就用實際的例子來給予說明。

 

1.     首先創建一個Android Project,並制定生成一個Activity,取名為Compare2Images

2.     將圖片androidlogo.png和xiaocheng.png拖入res/drawable-mdpi文件夾中,它們分別是:

        


3.     修改main.xml,使之如下

<?xml version="1.0"encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

>

   

    <ImageView android:id="@+id/iv_photo"

                android:layout_width="96dip"

                android:layout_height="96dip"

                android:src="@drawable/androidlogo"

    />

   

    <Button android:id="@+id/btn_photo"

                android:layout_width="93dip"

                android:layout_height="40dip"

                android:textSize="16dip"

                android:text="OK"

    />

</LinearLayout>

 

不難看出,在main.xml中有一個ImageView對象,該對象中顯示的圖片是@drawable/androidlogo,其下是一個按鈕。這個實驗的意圖是:

a.     當touch down ImageView對象時,首先獲取ImageView中顯示的圖像,然後啟動另外一個Activity(用來模擬照相機程序),該activity返回另外一個圖片(用xiaocheng.png模擬),Compare2Images在OnActivityResult方法中獲取返回的圖像後,將其顯示在ImageView對象iv_photo中

b.     當touch down OK按鈕btn_photo時(用來模擬保存數據的動作),再次從iv_photo中獲取圖像,然後和a中獲得的圖像進行比較,並進行進一步的處理。

 

4.     Compare2Images的代碼如下:

        package com.waveline.compare2images;

        import java.io.File;

        import java.io.FileNotFoundException;

        import java.io.FileOutputStream;

        import java.io.IOException;

        import android.app.Activity;

        import android.content.Intent;

        import android.graphics.Bitmap;

        import android.graphics.Bitmap.CompressFormat;

        import android.os.Bundle;

        import android.os.Environment;

        import android.view.MotionEvent;

        import android.view.View;

        import android.view.View.OnTouchListener;

        import android.widget.Button;

        import android.widget.ImageView;

        import android.widget.Toast;

        import android.widget.ImageView.ScaleType;

 

        public class Compare2Images extends Activity

        implements

        OnTouchListener

        {

                private Bitmap obmp;

                private ImageView iv_photo;

                private Button btn_photo;

                @Override

                public void onCreate(BundlesavedInstanceState)

                {

                        super.onCreate(savedInstanceState);

                        setContentView(R.layout.main);

       

                        iv_photo =(ImageView)findViewById(R.id.iv_photo);

                        iv_photo.setOnTouchListener(this);

 

                        btn_photo = (Button)findViewById(R.id.btn_photo);

                        btn_photo.setOnTouchListener(this);

               }

 

                public boolean onTouch(View v, MotionEventevent)

                {

                        switch(v.getId())

                        {

                        case R.id.iv_photo:

                               if(event.getAction() ==MotionEvent.ACTION_DOWN)

                               {

                                    // ImageView對象(iv_photo)必須做如下設置後,才能獲取其中的圖像

                                    iv_photo.setDrawingCacheEnabled(true);

                                   // 在ImageView對象(iv_photo)被touch down的時候,獲取ImageView中的圖像

                                   obmp = Bitmap.createBitmap(iv_photo.getDrawingCache());

                                   //然後在OK按鈕(btn_photo)被touch down的時候,比較ImaageView對象(iv_photo)中的圖像和

                                   //obmp是否一致,以便做進一步的處理,比如,如果不一致就保存,否則就不保存到數據庫中。

           

                                   //從ImaggeView對象中獲取圖像後,要記得調用setDrawingCacheEnabled(false)清空畫圖緩

                                   //沖區,否則,下一次用getDrawingCache()方法回去圖像時,還是原來的圖像

                                   iv_photo.setDrawingCacheEnabled(false);

          

                                   // 將得到obmp寫入文件

                                   FileOutputStream  m_fileOutPutStream = null;

                                   String filepath = Environment.getExternalStorageDirectory() +File.separator + "tempPhoto.png";

                                   try

                                   {

                                          m_fileOutPutStream= new FileOutputStream(filepath);

                                   }

                                   catch (FileNotFoundException e)

                                   {

                                          e.printStackTrace();

                                   }

          

                                   obmp.compress(CompressFormat.PNG, 100, m_fileOutPutStream);

          

                                   try

                                   {

                                             m_fileOutPutStream.flush();

                                             m_fileOutPutStream.close();

                                   }

                                   catch (IOException e)

                                   {

                                             e.printStackTrace();

                                   }

          

                                   Intent intent = new Intent(this, TakePicture.class);

                                   startActivityForResult(intent, 1);

                        }

                       break;

           case R.id.btn_photo:

                    if(event.getAction() ==MotionEvent.ACTION_DOWN)

                   {

                             // ImageView對象(iv_photo)必須做如下設置後,才能獲取其中的圖像

                             iv_photo.setDrawingCacheEnabled(true);

                             // 獲取ImageView中的圖像

                             Bitmap sbmp =Bitmap.createBitmap(iv_photo.getDrawingCache());

                             // 從ImaggeView對象(iv_photo)中獲取圖像後,要記得調用setDrawingCacheEnabled(false)

                            // 清空畫圖緩沖區


                            iv_photo.setDrawingCacheEnabled(false);     

                            

                             // 將得到sbmp寫入文件

                             FileOutputStream  m_fileOutPutStream = null;

                             String filepath = Environment.getExternalStorageDirectory() +File.separator + "tempPhoto1.png";

                             try

                             {

                                       m_fileOutPutStream= new FileOutputStream(filepath);

                             }

                             catch (FileNotFoundException e)

                             {

                                       e.printStackTrace();

                             }

          

                             sbmp.compress(CompressFormat.PNG, 100, m_fileOutPutStream);

          

                             try

                             {

                                       m_fileOutPutStream.flush();

                                       m_fileOutPutStream.close();

                             }

                             catch (IOException e)

                             {

                                       e.printStackTrace();

                             }

          

                             if(!compare2Image(obmp, sbmp))

                             {

                                   Toast.makeText(this, "new picture", Toast.LENGTH_LONG).show();

                             }

                             else

                             {

                                   Toast.makeText(this, "old picture", Toast.LENGTH_LONG).show();

                             }

                  }

                  break;

           }

           return false;

      }

 


      @Override

      protected void onActivityResult(int requestCode, int resultCode, Intent data)

      {

               if((requestCode == 1) &&(resultCode ==RESULT_FIRST_USER + 2))

              {

                  Bitmap ret_bitmap =data.getParcelableExtra("ret_bitmap");

                  iv_photo.setScaleType(ScaleType.FIT_XY);

                  iv_photo.setImageBitmap(ret_bitmap);

              }

           super.onActivityResult(requestCode,resultCode, data);

      }

 

      // 簡單的比較兩個圖像是否一致

    private boolean compare2Image(Bitmap bmp1,Bitmap bmp2)

    {

          int iteration = 0;

          int width = bmp1.getWidth();

          int height = bmp1.getHeight();

          if(width != bmp2.getWidth()) return false;

          if(height != bmp2.getHeight()) return false;

   

          if(width < height)

          {

                iteration = width;

          }

          else

          {

                iteration = height;

          }

          

          for(int i = 0; i < iteration; ++i)

         {              

                if(bmp1.getPixel(i, i) != bmp2.getPixel(i,i)) return false;

          }

          return true;

      }

}

 

5.     另外創建一個Activity,取名為TakePicture,並為它準備一個對應的layout文件takepicture.xml:

        <?xml version="1.0"encoding="utf-8"?>

        <LinearLayout

          xmlns:android="http://schemas.android.com/apk/res/android"

          android:layout_width="wrap_content"

          android:layout_height="wrap_content">

 

                 <Button android:id="@+id/btn_OK"

                          android:layout_width="90dip"

                          android:layout_height="40dip"

                          android:textSize="16dip"

                          android:text="OK"

                 />

        </LinearLayout>

 

6.     修改TakePicture.java,使其如下:

        package com.waveline.compare2images;

        import android.app.Activity;

        import android.content.Intent;

        import android.graphics.Bitmap;

        import android.graphics.BitmapFactory;

        import android.os.Bundle;

        import android.view.View;

        import android.view.View.OnClickListener;

        import android.widget.Button;

 

        public class TakePicture extends Activity

        implements

        OnClickListener

        {

                private Intent intent;

                private Button btn_OK;

 

                @Override

                protected void onCreate(BundlesavedInstanceState)

                {

                           super.onCreate(savedInstanceState);

                           setContentView(R.layout.takepicture);

          

                           btn_OK = (Button)findViewById(R.id.btn_OK);

                           btn_OK.setOnClickListener(this);

          

                           intent = getIntent();

                }

 

                public void onClick(View v)

                {

                           switch(v.getId())

                           {

                           case R.id.btn_OK:

                                 Bitmap ret_bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.xiaocheng);

                                 intent.putExtra("ret_bitmap", ret_bitmap);

                                 setResult(RESULT_FIRST_USER + 2, intent);

                                 finish();

                                 break;

                           }

                }

      }

 

7.     運行結果

 


Touch down ImageView對象後,會出現TakePicture的界面:

 


點擊OK按鈕,會將xiaocheng.png作為結果返回給Compare2Images,

 


點擊OK按鈕,對前後兩幅圖像進行比較:

 


結果顯示是一副新的圖像,即和原來的圖像時不一樣的。

 

如果在第一次調用getDrawingCache()方法從ImageView對象iv_photo獲取圖像之後,沒有調用setDrawingCacheEnabled(false)方法,盡管iv_photo顯示的圖片和原來的不同,但比較的結果總是一樣的,也就是說兩次調用getDrawingCache()方法所得到的結果是一樣的,這點應當特別需要註意。

 作者“玄機逸士的專欄”

發佈留言