安卓保存图片到sd卡报错

标签 android camera image sd-card

我有一个 Android 应用程序在某些手机上崩溃,而在其他手机上却没有。它有大约 5000 次下载,到目前为止已经收到大约 50 份崩溃报告。然而,根据我从用户那里得到的说它是强制崩溃的评级/评论数量,我认为受影响用户的百分比实际上要高得多。

由于该问题不影响我的手机,因此我无法重现错误并按我的意愿进行调试。

该应用程序从相机拍摄一张照片,在其上叠加一个位图,并将生成的图像保存到 SD 卡中。

下面是我的 onPictureTaken PictureCallback 方法的代码。

    private Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    public void onPictureTaken(byte[] data, Camera camera) {

        captureBtn.setVisibility(ImageButton.INVISIBLE); 

        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null){
            return;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap mutableBitmap = null;
        Bitmap finalBitmap = null; 
        byte[] byteArray = null; 
        try {   
            mutableBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options).copy(Bitmap.Config.RGB_565, true);
            Matrix matrix = new Matrix();
            int width = mutableBitmap.getWidth();
            int height = mutableBitmap.getHeight();
            int newWidth = overlayView.getDrawable().getBounds().width();
            int newHeight = overlayView.getDrawable().getBounds().height();
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            matrix.postScale(scaleWidth, scaleHeight);
            matrix.postRotate(90);

            Bitmap resizedBitmap = Bitmap.createBitmap(mutableBitmap, 0, 0, mutableBitmap.getWidth(), mutableBitmap.getHeight(), matrix, true);
            finalBitmap = resizedBitmap.copy(Bitmap.Config.RGB_565, true);
            Canvas canvas = new Canvas(finalBitmap);

            Bitmap overlayBitmap = null;
            if (mWeaponType == wep1) {
                overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wep1);
            } else if (mWeaponType == wep2) {
                overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wep2); 
            }

            if (overlayBitmap != null) {

                matrix = new Matrix();
                matrix.postRotate(90);
                Bitmap resizedOverlay = Bitmap.createBitmap(overlayBitmap, 0, 0, overlayBitmap.getWidth(), overlayBitmap.getHeight(), matrix, true);
                canvas.drawBitmap(resizedOverlay, 0, 0, new Paint());
                canvas.scale(50, 0);
                canvas.save();
                //finalBitmap is the image with the overlay on it

                // rotate image to save in landscape mode
                matrix = new Matrix(); 
                matrix.postRotate(270); 
                finalBitmap = Bitmap.createBitmap(finalBitmap, 0, 0, finalBitmap.getWidth(), finalBitmap.getHeight(), matrix,
                        true);

                // convert final bitmap to byte array
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byteArray = stream.toByteArray();
            }
        }

        catch(OutOfMemoryError e) {
            //fail
        }

        try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(byteArray); 
                fos.close();

                // Notify system that SD card has been updated
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
                Log.i(TAG, "Picture saved, intent broadcast that SD has been updated");
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        } catch (NullPointerException e) {

        }

        finally {
            mCamera.startPreview();
            captureBtn.setVisibility(ImageButton.VISIBLE);
        }
    }
};

我得到一个 NullPointerException 如下:

java.lang.NullPointerException
at java.io.FileOutputStream.write(FileOutputStream.java:256)
at com.mypackage.MyActivity.onPictureTaken(MyActivity.java:215)

这是

 fos.write(byteArray); 

行。

上面列出的getOutputMediaFile方法如下:

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    File mediaStorageDir = Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES);

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            Log.d("HalfLife2 Booth", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
        "IMG_"+ timeStamp + ".jpg");
    } else if(type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
        "VID_"+ timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}

我认为问题可能出在某处,试图获取输出媒体文件。我已尝试更新应用以使用:

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES), "MyApp");

相反,一位用户报告该问题已解决,但有几位用户报告该问题仍然存在。

任何想法,任何人?当我无法重现或接近它时,我发现这是一个很难调试/修复的问题。

最佳答案

确保以原始格式缩放图片。我发现某些手机型号的原始图像很大。如果图像非常大,我建议缩放图像,因为您将在运行虚拟机时耗尽内存。

例子:

     imageRef = sd_card_path+"/"+ImageName;
                BitmapFactory.Options resample = new BitmapFactory.Options();
                resample.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(imageRef, resample);
                int width = resample.outWidth;
                int height = resample.outHeight;
                if(width*height > utility.IMAGE_SIZE_MIN){
                    int imageSizef = (int)(width*height/utility.IMAGE_SIZE_MIN);
                    String imageSize = imageSizef+"";
                    resample.inSampleSize = Integer.parseInt(imageSize);
                    resample.inJustDecodeBounds = false;
                    image.setImageBitmap(BitmapFactory.decodeFile(imageRef , resample));                    
                }else{
                    image.setImageBitmap(BitmapFactory.decodeFile(imageRef ));
                }

关于安卓保存图片到sd卡报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245234/

相关文章:

用于 iframe 的 Android webView shouldOverrideUrlLoading

android - 将应用了主题对话框的 Activity 定位在特定的 x、y 位置

math - 使用 Eigen 计算 2D 相机的模型 View 矩阵

ios - 使用带有应用程序的 iPhone 控制外部摄像头

Java SWT - 禁用按钮上的图像

Android 默认的 SearchView 图标有一个奇怪的边框

java - 为什么即使 myLocation 是全局变量,当 onSuccess() 终止时 myLocation 也会变为 null?

android - 重新安装应用程序后有时无法释放相机

java - 如何消除通过将 jframe 图像捕获到文件而产生的边框?

ios - iOS 11 UIBarButtonItem ImageView大小错误