为什么在从Android摄像头捕获图像时,在自定义维度的SD卡文件夹中保存图像时崩溃Android应用程序?

时间:2014-05-20 14:02:35

标签: android android-camera image-resizing android-sdcard android-camera-intent

我尝试在从Android相机捕获图像后使用自定义尺寸(宽x高)保存在SD卡文件夹中,然后应用程序崩溃。

我的MainActivity.java如下:

import com.example.imageresizefromcamera.MainActivity.ScalingUtilities.ScalingLogic;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 0;
    public String imageName, imagePath;
    File direct;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void captureImage(View v) {

        direct = new File(Environment.getExternalStorageDirectory()
                + "/YourFolder");

        if (!direct.exists()) {
            if (direct.mkdir()) {
                // directory is created;
            }   
        }

        SecureRandom random = new SecureRandom();
        String randomName = new BigInteger(10, random).toString(4);
        imageName = "myImage" + "" + randomName + ".JPEG";
        File file = new File(direct, imageName);

        imagePath = file.getAbsolutePath();
        Uri outputFileUri = Uri.fromFile(file);
        Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(i, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

    }

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

        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                getScaledBitMap(imagePath, 1536, 2048);
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        } else {
            //
        }
    }

    private Bitmap getScaledBitMap(String filePath, int reqWidth, int reqHeight) {

        if (filePath != null && filePath.contains("file")) {
            filePath = filePath.replace("file://", "");
        }
        Bitmap unscaledBitmap = ScalingUtilities.decodeBitmap(getResources(),
                filePath, reqWidth, reqHeight, ScalingLogic.CROP);
        // Part 2: Scale image
        Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(
                unscaledBitmap, reqWidth, reqHeight, ScalingLogic.CROP);
        unscaledBitmap.recycle();

        // convert and save sd card folder

        try {
            OutputStream fOut = null;
            File file = new File(direct, imageName);
            fOut = new FileOutputStream(file);
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
            fOut.flush();
            fOut.close();
            MediaStore.Images.Media.insertImage(getContentResolver(),
                    file.getAbsolutePath(), file.getName(), file.getName());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return scaledBitmap;

    }

    public static class ScalingUtilities {

        /**
         * Utility function for decoding an image resource. The decoded bitmap
         * will be optimized for further scaling to the requested destination
         * dimensions and scaling logic.
         * 
         * @param res
         *            The resources object containing the image data
         * @param resId
         *            The resource id of the image data
         * @param dstWidth
         *            Width of destination area
         * @param dstHeight
         *            Height of destination area
         * @param scalingLogic
         *            Logic to use to avoid image stretching
         * @return Decoded bitmap
         */
        public static Bitmap decodeBitmap(Resources res, String pathName,
                int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
            Options options = new Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(pathName, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateSampleSize(options.outWidth,
                    options.outHeight, dstWidth, dstHeight, scalingLogic);
            Bitmap unscaledBitmap = BitmapFactory.decodeFile(pathName, options);

            return unscaledBitmap;
        }

        /**
         * Utility function for creating a scaled version of an existing bitmap
         * 
         * @param unscaledBitmap
         *            Bitmap to scale
         * @param dstWidth
         *            Wanted width of destination bitmap
         * @param dstHeight
         *            Wanted height of destination bitmap
         * @param scalingLogic
         *            Logic to use to avoid image stretching
         * @return New scaled bitmap object
         */
        public static Bitmap createScaledBitmap(Bitmap unscaledBitmap,
                int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
            Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(),
                    unscaledBitmap.getHeight(), dstWidth, dstHeight,
                    scalingLogic);
            Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(),
                    unscaledBitmap.getHeight(), dstWidth, dstHeight,
                    scalingLogic);
            Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(),
                    dstRect.height(), Config.ARGB_8888);
            Canvas canvas = new Canvas(scaledBitmap);
            canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(
                    Paint.FILTER_BITMAP_FLAG));

            return scaledBitmap;
        }


        public static enum ScalingLogic {
            CROP, FIT
        }


        public static int calculateSampleSize(int srcWidth, int srcHeight,
                int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
            if (scalingLogic == ScalingLogic.FIT) {
                final float srcAspect = (float) srcWidth / (float) srcHeight;
                final float dstAspect = (float) dstWidth / (float) dstHeight;

                if (srcAspect > dstAspect) {
                    return srcWidth / dstWidth;
                } else {
                    return srcHeight / dstHeight;
                }
            } else {
                final float srcAspect = (float) srcWidth / (float) srcHeight;
                final float dstAspect = (float) dstWidth / (float) dstHeight;

                if (srcAspect > dstAspect) {
                    return srcHeight / dstHeight;
                } else {
                    return srcWidth / dstWidth;
                }
            }
        }

        public static Rect calculateSrcRect(int srcWidth, int srcHeight,
                int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
            if (scalingLogic == ScalingLogic.CROP) {
                final float srcAspect = (float) srcWidth / (float) srcHeight;
                final float dstAspect = (float) dstWidth / (float) dstHeight;

                if (srcAspect > dstAspect) {
                    final int srcRectWidth = (int) (srcHeight * dstAspect);
                    final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
                    return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth,
                            srcHeight);
                } else {
                    final int srcRectHeight = (int) (srcWidth / dstAspect);
                    final int scrRectTop = (int) (srcHeight - srcRectHeight) / 2;
                    return new Rect(0, scrRectTop, srcWidth, scrRectTop
                            + srcRectHeight);
                }
            } else {
                return new Rect(0, 0, srcWidth, srcHeight);
            }
        }

        public static Rect calculateDstRect(int srcWidth, int srcHeight,
                int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
            if (scalingLogic == ScalingLogic.FIT) {
                final float srcAspect = (float) srcWidth / (float) srcHeight;
                final float dstAspect = (float) dstWidth / (float) dstHeight;

                if (srcAspect > dstAspect) {
                    return new Rect(0, 0, dstWidth,
                            (int) (dstWidth / srcAspect));
                } else {
                    return new Rect(0, 0, (int) (dstHeight * srcAspect),
                            dstHeight);
                }
            } else {
                return new Rect(0, 0, dstWidth, dstHeight);
            }
        }

    }

}

以及我的AndroidMenifest.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.imageresizefromcamera"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.imageresizefromcamera.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LogCat错误消息:

05-20 20:09:50.139: E/AndroidRuntime(19158): FATAL EXCEPTION: main
05-20 20:09:50.139: E/AndroidRuntime(19158): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.graphics.Bitmap.nativeCreate(Native Method)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.graphics.Bitmap.createBitmap(Bitmap.java:477)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at com.example.imageresizefromcamera.MainActivity$ScalingUtilities.createScaledBitmap(MainActivity.java:179)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at com.example.imageresizefromcamera.MainActivity.getScaledBitMap(MainActivity.java:99)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at com.example.imageresizefromcamera.MainActivity.onActivityResult(MainActivity.java:74)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.app.Activity.dispatchActivityResult(Activity.java:3914)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2540)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:2586)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.app.ActivityThread.access$2000(ActivityThread.java:117)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.os.Looper.loop(Looper.java:130)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at android.app.ActivityThread.main(ActivityThread.java:3695)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at java.lang.reflect.Method.invokeNative(Native Method)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at java.lang.reflect.Method.invoke(Method.java:507)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
05-20 20:09:50.139: E/AndroidRuntime(19158):    at dalvik.system.NativeStart.main(Native Method)
05-20 20:09:50.139: E/ActivityManager(192): exception bw.write()java.io.IOException: Transport endpoint is not connected

其实我想要一些事情。比如 1.从Android相机拍摄图像 2.调整自定义尺寸(1536 X 2048) 3.最后保存在SD卡文件夹中(使用1536 X 2048)。

请帮助我任何人。如果我的程序错了,那么你可以编辑我的问题/代码。但回答对我来说至关重要。

0 个答案:

没有答案