天天看點

Android:處理調用系統相機照片被壓縮問題

最近使用Intent調用系統的拍照功能,并用onActivityResult方法中的data得到照片的bitmap,但是發現擷取的照片資源是被壓縮過的,而且被壓縮的很小,那麼如何得到未被壓縮的原圖檔并按照自己的需要進行壓縮呢?

在網上找了一些方法,那就是在跳轉時添加intentPhote.putExtra(MediaStore.EXTRA_OUTPUT, uri); 這個屬性,這種方式的過程就是将拍攝的圖檔存儲到uri這個路徑中,而onActivityResult隻是負責顯示這個照片,也就是說是提前确定存儲的路徑。下面上代碼

<pre name="code" class="java">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.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private Button mButton;
    private ImageView mImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button) findViewById(R.id.button1);
        mImage = (ImageView) findViewById(R.id.image_show);
        mButton.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // 跳轉至拍照界面
                Intent intentPhote = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intentPhote.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                File out = new File(getPhotopath());
                Uri uri = Uri.fromFile(out);
                // 擷取拍照後未壓縮的原圖檔,并儲存在uri路徑中
                intentPhote.putExtra(MediaStore.EXTRA_OUTPUT, uri); 
//                intentPhote.putExtra(MediaStore.Images.Media.ORIENTATION, 180);
                startActivityForResult(intentPhote, 2000);
            }
        });
    }
    /**
     * 擷取原圖檔存儲路徑
     * @return
     */
    private String getPhotopath() {
        // 照片全路徑
        String fileName = "";
        // 檔案夾路徑
        String pathUrl = Environment.getExternalStorageDirectory()+"/mymy/";
        String imageName = "imageTest.jpg";
        File file = new File(pathUrl);
        file.mkdirs();// 建立檔案夾
        fileName = pathUrl + imageName;
        return fileName;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 2000 && resultCode == Activity.RESULT_OK) {
            Bitmap bitmap = getBitmapFromUrl(getPhotopath(), 313.5, 462.0);
            saveScalePhoto(bitmap);
            mImage.setImageBitmap(bitmap);
        }
    }
    /**
     * 根據路徑擷取圖檔資源(已縮放)
     * @param url 圖檔存儲路徑
     * @param width 縮放的寬度
     * @param height 縮放的高度
     * @return
     */
    private Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 設定了此屬性一定要記得将值設定為false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 防止OOM發生
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;
//        try {
//            ExifInterface exif = new ExifInterface(url);
//            String model = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 按照固定寬高進行縮放
        // 這裡希望知道照片是橫屏拍攝還是豎屏拍攝
        // 因為兩種方式寬高不同,縮放效果就會不同
        // 這裡用了比較笨的方式
        if(mWidth <= mHeight) {
            scaleWidth = (float) (width/mWidth);
            scaleHeight = (float) (height/mHeight);
        } else {
            scaleWidth = (float) (height/mWidth);
            scaleHeight = (float) (width/mHeight);
        }
//        matrix.postRotate(90); /* 翻轉90度 */
        // 按照固定大小對圖檔進行縮放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 用完了記得回收
        bitmap.recycle();
        return newBitmap;
    }
    
    /**
     * 存儲縮放的圖檔
     * @param data 圖檔資料
     */
    private void saveScalePhoto(Bitmap bitmap) {
        // 照片全路徑
        String fileName = "";
        // 檔案夾路徑
        String pathUrl = Environment.getExternalStorageDirectory().getPath()+"/mymy/";
        String imageName = "imageScale.jpg";
        FileOutputStream fos = null;
        File file = new File(pathUrl);
        file.mkdirs();// 建立檔案夾
        fileName = pathUrl + imageName;
        try {
            fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
           

布局比較簡單

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="拍照" />
    
    <ImageView 
        android:id="@+id/image_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
           

最後别忘了添權重限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

這樣就能按照自己的需要存儲特定大小的照片了