android解決堅屏拍照和保存圖片旋轉90度的問題,並兼容4.0


 第一步: AndroidManifest.xml 在Activity添加以下一個屬性

android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="sensor",為的是能夠橫豎屏切換不用再次調用onCreate方法,直接調用onConfigurationChanged方法。screenSize是兼容4.0系統的才可以生效,否則方法沒效。
<application android:label="@string/app_name"
        android:icon="@drawable/ic_launcher">
       <activity android:name=".MainActivity"  
                  android:label="@string/app_name"
                  android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="sensor">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity> 
    </application>

第二步,解決豎屏拍照后保存圖片會旋轉90度的問題。這里我會在onConfigurationChanged方法進行判斷當前是橫拍還是豎拍,然后在調用相機拍照后,在保存圖片的方法里,進行豎拍的照片90度旋轉。

     

PictureCallback jpeg = new PictureCallback() {  
          
        @Override  
        public void onPictureTaken(byte[] data, Camera camera) {  
            // TODO Auto-generated method stub  
        	 Bitmap bMap; 
            try  
            {// 獲得圖片  
            	 
    	        
    	        bMap = BitmapFactory.decodeByteArray(data, 0, data.length);  
    	         
    	        Bitmap bMapRotate;  
    	        if (takeType != 0) {  //堅拍
    	            Matrix matrix = new Matrix();  
    	            matrix.reset();  
    	            matrix.postRotate(90);  
    	            bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(),  
    	                    bMap.getHeight(), matrix, true); 
    	            bMap = bMapRotate;
    	        }
          
           // Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);  
            File file = new File(filePath);  
            BufferedOutputStream bos =  
                new BufferedOutputStream(new FileOutputStream(file));  
            bMap.compress(Bitmap.CompressFormat.JPEG, 100, bos);//將圖片壓縮到流中  
            bos.flush();//輸出  
            bos.close();//關閉  
            }catch(Exception e)  
            {  
                e.printStackTrace();  
            }  
              
        }  
    };  

  關鍵代碼是以上。

 

 當用豎拍轉橫拍,還是橫拍轉豎拍,都要先在surfaceChanged方法,停止預覽相機,重新設置下攝像頭就不會再出現90度旋轉。

  

源碼下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM